hooks.js 2.8 KB

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