hooks.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. const graphHelper = require('../../helpers/graph')
  2. const _ = require('lodash')
  3. /* global WIKI */
  4. module.exports = {
  5. Query: {
  6. async hooks () {
  7. return WIKI.models.hooks.query().orderBy('name')
  8. },
  9. async hookById (obj, args) {
  10. return WIKI.models.hooks.query().findById(args.id)
  11. }
  12. },
  13. Mutation: {
  14. /**
  15. * CREATE HOOK
  16. */
  17. async createHook (obj, args) {
  18. try {
  19. // -> Validate inputs
  20. if (!args.name || args.name.length < 1) {
  21. throw WIKI.ERROR(new Error('Invalid Hook Name'), 'HookCreateInvalidName')
  22. }
  23. if (!args.events || args.events.length < 1) {
  24. throw WIKI.ERROR(new Error('Invalid Hook Events'), 'HookCreateInvalidEvents')
  25. }
  26. if (!args.url || args.url.length < 8 || !args.url.startsWith('http')) {
  27. throw WIKI.ERROR(new Error('Invalid Hook URL'), 'HookCreateInvalidURL')
  28. }
  29. // -> Create hook
  30. const newHook = await WIKI.models.hooks.createHook(args)
  31. return {
  32. operation: graphHelper.generateSuccess('Hook created successfully'),
  33. hook: newHook
  34. }
  35. } catch (err) {
  36. return graphHelper.generateError(err)
  37. }
  38. },
  39. /**
  40. * UPDATE HOOK
  41. */
  42. async updateHook (obj, args) {
  43. try {
  44. // -> Load hook
  45. const hook = await WIKI.models.hooks.query().findById(args.id)
  46. if (!hook) {
  47. throw WIKI.ERROR(new Error('Invalid Hook ID'), 'HookInvalidId')
  48. }
  49. // -> Check for bad input
  50. if (_.has(args.patch, 'name') && args.patch.name.length < 1) {
  51. throw WIKI.ERROR(new Error('Invalid Hook Name'), 'HookCreateInvalidName')
  52. }
  53. if (_.has(args.patch, 'events') && args.patch.events.length < 1) {
  54. throw WIKI.ERROR(new Error('Invalid Hook Events'), 'HookCreateInvalidEvents')
  55. }
  56. if (_.has(args.patch, 'url') && (_.trim(args.patch.url).length < 8 || !args.patch.url.startsWith('http'))) {
  57. throw WIKI.ERROR(new Error('URL is invalid.'), 'HookInvalidURL')
  58. }
  59. // -> Update hook
  60. await WIKI.models.hooks.query().findById(args.id).patch(args.patch)
  61. return {
  62. operation: graphHelper.generateSuccess('Hook updated successfully')
  63. }
  64. } catch (err) {
  65. return graphHelper.generateError(err)
  66. }
  67. },
  68. /**
  69. * DELETE HOOK
  70. */
  71. async deleteHook (obj, args) {
  72. try {
  73. await WIKI.models.hooks.deleteHook(args.id)
  74. return {
  75. operation: graphHelper.generateSuccess('Hook deleted successfully')
  76. }
  77. } catch (err) {
  78. return graphHelper.generateError(err)
  79. }
  80. }
  81. }
  82. }