apollo-link-scalars
TypeDoc generated docs in here
Github repo here
Custom Apollo Link to allow to parse custom scalars from responses, as well as serialize custom scalars in inputs. It can also validate enums, and cleanup __typename
from inputs. (see Usage and Options).
Disclaimer: Potential cache interaction
Parsing scalars at link level means that Apollo cache will receive them already parsed. Depending on what kind of parsing is performed, this may interact with the cache JSON serialization of, for example,apollo-cache-persist
. While apollo-cache-persist
has an option to turn that serialisation off, others may have similar issues.
In the original Apollo Client Github issue thread about scalar parsing, this situation was discussed.
At the time of this writing, Apollo Client still does not support this over 4 years after the original ticket was opened. A potential solution of parsing after the cache might have some other issues, like returning different instances for the cached data, which may not be ideal in some situations that rely on that (e.g. react re-render control). I think some users will benefit more from the automatic parsing and serializing than the cost of the potential cache interactions.
Installation
yarn add apollo-link-scalars
or npm install apollo-link-scalars
.
Usage
We need to pass a GraphQLSchema
, and optionally we can also pass a map of custom serialization/parsing functions for specific types.
You can build the link by calling the withScalars()
function, passing to it the schema
and optionally a typesMap
.
import { withScalars } from "apollo-link-scalars";
import { ApolloLink } from "apollo-link";
import { HttpLink } from "apollo-link-http";
import { schema } from "./my-schema";
const link = ApolloLink.from([
withScalars({ schema }),
new HttpLink({ uri: "http://example.org/graphql" })
]);
const typesMap = {
CustomScalar: {
serialize: (parsed: CustomScalar) => parsed.toString(),
parseValue: (raw: string | number | null): CustomScalar | null => {
return raw ? new CustomScalar(raw) : null;
}
}
};
const link2 = ApolloLink.from([
withScalars({ schema, typesMap }),
new HttpLink({ uri: "http://example.org/graphql" })
]);
Options
We can pass extra options to withScalars()
to modify the behaviour
removeTypenameFromInputs
(Boolean
, default false
): when enabled, it will remove from the inputs the __typename
if it is found. This could be useful if we are using data received from a query as an input on another query.validateEnums
(Boolean
, default false
): when enabled, it will validate the enums on parsing, throwing an error if it sees a value that is not one of the enum values.
withScalars({
schema,
typesMap,
validateEnums: true,
removeTypenameFromInputs: true
});
Example of loading a schema
import gql from "graphql-tag";
import { GraphQLScalarType, Kind } from "graphql";
import { makeExecutableSchema } from "apollo-link-scalars";
const typeDefs = gql`
type Query {
myList: [MyObject!]!
}
type MyObject {
day: Date
days: [Date]!
nested: MyObject
}
"represents a Date with time"
scalar Date
`;
const resolvers = {
Date: new GraphQLScalarType({
name: "Date",
serialize: (parsed: CustomDate | null) => parsed && parsed.toISOString(),
parseValue: (raw: any) => raw && new CustomDate(new Date(raw)),
parseLiteral(ast) {
if (ast.kind === Kind.STRING || ast.kind === Kind.INT) {
return new CustomDate(new Date(ast.value));
}
return null;
}
})
};
const schema = makeExecutableSchema({
typeDefs,
resolvers
});
Synchronously creating a link instance with graphql-code-generator
setup
Warning: Be sure to watch your bundle size and know what you are doing.
Codegen config to generate introspection data:
codegen.yml
---
generates:
src/__generated__/graphql.schema.json:
plugins:
- "introspection"
config:
minify: true
Synchronous code to create link instance in common scenario:
import introspectionResult from "./__generated__/graphql.schema.json";
import { buildClientSchema, IntrospectionQuery } from "graphql";
const schema = buildClientSchema(introspectionResult)
const scalarsLink = withScalars({
schema,
typesMap: { … },
});
Acknowledgements
The link code is heavily based on apollo-link-response-resolver
by will-heart.
While the approach in apollo-link-response-resolver
is to apply resolvers based on the types taken from __typename
, this follows the query and the schema to parse based on scalar types. Note that apollo-link-response-resolver
is archived now
I started working on this after following the Apollo feature request https://github.com/apollographql/apollo-feature-requests/issues/2.
Development, Commits, versioning and publishing
See documentation for development
See The Typescript-Starter docs.
Commits and CHANGELOG
For commits, you should use commitizen
yarn global add commitizen
git cz
As typescript-starter docs state:
This project is tooled for conventional changelog to make managing releases easier. See the standard-version documentation for more information on the workflow, or CHANGELOG.md
for an example.
yarn run version
You may find a tool like wip
helpful for managing work in progress before you're ready to create a meaningful commit.
Creating the first version
Once you are ready to create the first version, run the following (note that reset
is destructive and will remove all files not in the git repo from the directory).
yarn run reset && yarn run test && yarn run doc:html
yarn run version -- --first-release
And after that, remember to publish the docs.
And finally push the new tags to github and publish the package to npm.
git push --follow-tags origin master
yarn publish --access public
Publish the Docs
yarn run doc:html && yarn run doc:publish
This will generate the docs and publish them in github pages.
Generate a version
There is a single yarn command for preparing a new release. See One-step publish preparation script in TypeScript-Starter
yarn prepare-release
git push --follow-tags origin master
yarn publish --access public
Contributors ✨
Thanks goes to these wonderful people (emoji key):
This project follows the all-contributors specification. Contributions of any kind welcome!