helpers.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. import { ApolloServer } from 'apollo-server-express'
  2. import { GraphQLResponse } from 'apollo-server-core'
  3. type TypedGraphQLResponse<TResult> = GraphQLResponse & {
  4. data?: TResult | null
  5. }
  6. export const createQueryFn = (server: ApolloServer) => {
  7. type QueryOpts<TVars> = {
  8. query: Parameters<typeof server.executeOperation>[0]['query']
  9. // eslint-disable-next-line @typescript-eslint/ban-types
  10. } & (TVars extends undefined ? {} : { variables: TVars })
  11. return async <TResult, TVars = undefined>(opts: QueryOpts<TVars>) => {
  12. const result = await server.executeOperation(opts)
  13. return result as TypedGraphQLResponse<TResult>
  14. }
  15. }
  16. export const createMutationFn = (server: ApolloServer) => {
  17. type MutationOpts<TVars> = {
  18. mutation: Parameters<typeof server.executeOperation>[0]['query']
  19. variables: TVars
  20. }
  21. return async <TResult, TVars>(opts: MutationOpts<TVars>) => {
  22. const result = await server.executeOperation({ ...opts, query: opts.mutation })
  23. return result as TypedGraphQLResponse<TResult>
  24. }
  25. }
  26. export type QueryFn = ReturnType<typeof createQueryFn>
  27. export type MutationFn = ReturnType<typeof createMutationFn>