Skip to content

Latest commit

 

History

History
98 lines (77 loc) · 2.81 KB

custom-functions.md

File metadata and controls

98 lines (77 loc) · 2.81 KB

Custom Query and Mutation functions

Sometimes it's necessary to extend GraphQL-Pouch's base functionality with your own project specific implementations. The code must be written in a “stateless” style i.e. it should assume there is no affinity to the underlying runtime. In-Memory state, local file system access, child processes, and similar artifacts may not extend beyond the lifetime of the request, and any persistent state should be stored in PouchDB, or another internet-available storage service. Custom functions can include NPM modules to access external infrastructure components.

Use custom function for:

  • Fetch data from third-party data source e.g. RESTful services, Databases, etc.
  • Mutation query Input-Validation
  • Data query filters/ordering
  • Data query transformations e.g. cleansing or enhancements
  • Forwarding mutation commands to your Backends
  • Business logic implementations
  • etc.

There are two different depth levels to enhance GraphQL-Pouch to replace existing or define new queries and mutations.

Register custom functions via CLI

Here is a full example to replace a GrpahQL-Pouch generated Mutation with your own implementation.

  • Create or modify your GraphQL-Pouch shorthand notation schema. Skip this if your own schema already exists.

myschema.graphql

type Service {
  id: ID!
  rev: String
}

Register your schema with the --schema CLI argument

graphql-pouch ---schema myschema.graphql
  • Create a file named by query or mutation you want to support, respectively replace, in your GraphQL-Schema. There is a simple convention for custom function naming:

operation name + type name + .js

For instance: replace the upsert-Mutation for the Service-Type

upsertService.js

module.exports = (ctx, input) => {

  // Build Relay compliant `UpsertSettingPayload` result
  const result = {
    upsertedServiceId: input.input.id,
    clientMutationId: input.input.clientMutationId,
    service: {
      id: input.input.id,
      rev: '',
    },
    serviceEdge: {
      cursor: 0,
      node: {
        id: input.input.id,
        rev: '',
      }
    }
  };

  // Send result to Relay compliant client
  ctx.success(result);
}
  • Afterward register the function with the --function CLI argument.
graphql-pouch --function upsertService.js
  • Start graphql-pouch --development, navigate to the displayed GraphiQL URL and enter
mutation {
  upsertService(input: {id: "my-client-generated-id", clientMutationId: "my-client-generated-id"}) {
    upsertedServiceId
    clientMutationId
    service {
      id
      rev
    }
    serviceEdge {
      cursor
      node {
        id
        rev
      }
    }
  }
}