Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Sequelize from 'sequelize'
- import { combineResolvers } from 'graphql-resolvers'
- import { isAuthenticated, isCommentOwner } from './authorization'
- const toCursorHash = string => Buffer.from(string).toString('base64')
- const fromCursorHash = string => Buffer.from(string, 'base64').toString('ascii')
- export default {
- Query: {
- comments: async (parent, { cursor, limit, storyId }, { models }) => {
- const cursorOptions = cursor
- ? {
- createdAt: {
- [Sequelize.Op.lt]: fromCursorHash(cursor),
- },
- }
- : {}
- const comments = await models.Comment.findAll({
- order: [['createdAt', 'DESC']],
- limit: limit + 1,
- where: {
- ...cursorOptions,
- storyId,
- commentId: null,
- },
- })
- const hasNextPage = comments.length > limit
- const edges = hasNextPage ? comments.slice(0, -1) : comments
- const lastComment = comments[comments.length - 1]
- const endCursor = lastComment
- ? toCursorHash(lastComment.createdAt.toString())
- : ''
- return {
- edges,
- pageInfo: {
- hasNextPage,
- endCursor,
- },
- }
- },
- comment: async (parent, args, ctx) =>
- await ctx.models.Comment.findByPk(args.id),
- },
- Mutation: {
- createComment: combineResolvers(
- isAuthenticated,
- async (parent, { body, id, commentId }, ctx) =>
- await ctx.models.Comment.create({
- userId: ctx.request.userId,
- storyId: id,
- commentId,
- body,
- })
- ),
- updateComment: combineResolvers(
- isAuthenticated,
- isCommentOwner,
- async (parent, { id, body }, ctx) => {
- const comment = await ctx.models.Comment.findByPk(id)
- return await comment.update({ body })
- }
- ),
- deleteComment: combineResolvers(
- isAuthenticated,
- isCommentOwner,
- async (parent, { id }, ctx) => {
- const comment = await ctx.models.Comment.findByPk(id)
- await ctx.models.Comment.destroy({
- where: {
- id,
- },
- })
- return comment
- }
- ),
- },
- Comment: {
- user: async (comment, args, { loaders }) =>
- await loaders.user.load(comment.userId),
- branch: async (comment, args, { models }) => {
- const comments = await models.Comment.findAll({
- where: {
- commentId: comment.id,
- },
- })
- return comments
- },
- },
- }
Advertisement
Add Comment
Please, Sign In to add comment