apollo-type-patcher
Utility to generate Type Patcher functions for apollo-link-rest.
Jump to: Goal | Installation | Usage | How it works | Features | Contribute
Goal
The apollo-link-rest library enables a smooth, frontend-first transition into GraphQL, by allowing you to leverage this query language in a project powered by a REST API (read some of the reasons here). However, since you don't have a schema for your type definitions (because you don't have a GraphQL server), you have to generate the type patcher functions yourself. This is a very verbose, time consuming and error-prone process, specially if you're trying to consume endpoints with a lot of nested fields whose types you want to normalize into the cache.
The goal of this apollo-type-patcher
library is to generate the type patcher functions easily and in a safe maintanable way, with an object contaiting your type definition mappings.
Installation
To add this library to your project's dependencies
simply run:
yarn add apollo-type-patcher
Usage
Try it out in the browser(soon!)
- Create your type definitions object. This object is in the form of
typeDefinitions = TYPE: FIELD: TYPE ... ...
for example:
// typeDefinitions.jsconst typeDefinitions = Student: classes: Class extra_activities: Activities Class: chair_professor: Professor
- When setting up your Apollo link rest configuration, add the type patcher as follows:
import typePatcher from "apollo-type-patcher";import RestLink from "apollo-link-rest";// your type definitionsimport typeDefinitions from "./typeDefinitions"; const restLink = typePatcher: ...;
How it works
The type patcher adds the typename property to nested types, since the root type is injected directly by Apollo:
// for the Query:const GET_STUDENT = gql` query getStudent($id: ID!) { student(id: $id) @rest(type: "Student", path: "student/{args.id}") { id degree { id } } }`; // and for the type defintions:typeDefinitions = Student: degree: Degree // the output of the Apollo request (pre type patching) is:student = id: 60 degree: id: 5 __typename: "Student" // <- Added by Apollo directly // the final of the Query (pos type patching) is:student = id: 60 degree: id: 5 __typename: "Degree" // <- Added by the typePatcher __typename: "Student"
Features
- add types in nested objects
// typeDefStudent: class: "Class"// outstudent: class: __typename: "Class"
- add types in nested arrays
// typeDefStudent: topics: "Topic"// outstudent: topics: __typename: "Topic" ...
- add types in deeply nested properties
// typeDefStudent: "needs.medical_needs.insurance": "Insurance"// outstudent: needs: medical_needs: insurance: __typename: "Insurance"
Contribute
After cloning the repo locally, you can run:
yarn // install dependenciesyarn build // build the bundle w/webpackyarn test // run unit tests