Guest User

Untitled

a guest
Apr 20th, 2019
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.53 KB | None | 0 0
  1. import Sequelize from 'sequelize'
  2. import { combineResolvers } from 'graphql-resolvers'
  3. import { isAuthenticated, isCommentOwner } from './authorization'
  4.  
  5. const toCursorHash = string => Buffer.from(string).toString('base64')
  6.  
  7. const fromCursorHash = string => Buffer.from(string, 'base64').toString('ascii')
  8.  
  9. export default {
  10. Query: {
  11. comments: async (parent, { cursor, limit, storyId }, { models }) => {
  12. const cursorOptions = cursor
  13. ? {
  14. createdAt: {
  15. [Sequelize.Op.lt]: fromCursorHash(cursor),
  16. },
  17. }
  18. : {}
  19. const comments = await models.Comment.findAll({
  20. order: [['createdAt', 'DESC']],
  21. limit: limit + 1,
  22. where: {
  23. ...cursorOptions,
  24. storyId,
  25. commentId: null,
  26. },
  27. })
  28. const hasNextPage = comments.length > limit
  29. const edges = hasNextPage ? comments.slice(0, -1) : comments
  30. const lastComment = comments[comments.length - 1]
  31. const endCursor = lastComment
  32. ? toCursorHash(lastComment.createdAt.toString())
  33. : ''
  34. return {
  35. edges,
  36. pageInfo: {
  37. hasNextPage,
  38. endCursor,
  39. },
  40. }
  41. },
  42.  
  43. comment: async (parent, args, ctx) =>
  44. await ctx.models.Comment.findByPk(args.id),
  45. },
  46.  
  47. Mutation: {
  48. createComment: combineResolvers(
  49. isAuthenticated,
  50. async (parent, { body, id, commentId }, ctx) =>
  51. await ctx.models.Comment.create({
  52. userId: ctx.request.userId,
  53. storyId: id,
  54. commentId,
  55. body,
  56. })
  57. ),
  58.  
  59. updateComment: combineResolvers(
  60. isAuthenticated,
  61. isCommentOwner,
  62. async (parent, { id, body }, ctx) => {
  63. const comment = await ctx.models.Comment.findByPk(id)
  64. return await comment.update({ body })
  65. }
  66. ),
  67.  
  68. deleteComment: combineResolvers(
  69. isAuthenticated,
  70. isCommentOwner,
  71. async (parent, { id }, ctx) => {
  72. const comment = await ctx.models.Comment.findByPk(id)
  73. await ctx.models.Comment.destroy({
  74. where: {
  75. id,
  76. },
  77. })
  78. return comment
  79. }
  80. ),
  81. },
  82.  
  83. Comment: {
  84. user: async (comment, args, { loaders }) =>
  85. await loaders.user.load(comment.userId),
  86.  
  87. branch: async (comment, args, { models }) => {
  88. const comments = await models.Comment.findAll({
  89. where: {
  90. commentId: comment.id,
  91. },
  92. })
  93.  
  94. return comments
  95. },
  96. },
  97. }
Advertisement
Add Comment
Please, Sign In to add comment