Connecting the Client and the Server

June 28th, 2020 By Alex Hu

main

Apollo Client

For the Add / Edit / Delete, the client uses useMutation() to trigger a mutation.

const [updateArticle] = useMutation(UpdateArticleMutation)

const changes = {
  ...article,
  title,
  summary,
  content,
}
await updateArticle({ variables: changes })

Apollo GraphQL Resolvers

The server side implements the resolver with just a few lines:

async updateArticle(_parent: any, args: any, _context: any, _info: any) {
  // console.log('updateArticle -> args', args)
  await dbConnect()
  args.input.updatedAt = (new Date()).toISOString()
  const article = await Article.findByIdAndUpdate(args.input.id, args.input, { new: true })
  return migrateArticle(article)
},

The dbConnect() function makes the database connection and retries up to 10 times.

The migrateArticle() function migrates old data by adding the additional fields that were not in the initial data model, such as the createdAt, updatedAt and section fields.