• Stars
    star
    157
  • Rank 238,399 (Top 5 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 5 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

custom apollo link to allow to parse custom scalars

apollo-link-scalars

All Contributors

npm version Build Status codebeat badge Maintainability Test Coverage

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).

Library Versions

Apollo Client v2 -> apollo-link-scalars v0.x

The deprecated Apollo Client v2 is used in the 0.x branch.

Of the 0.x family, the versions 0.1.x and 0.2.x are deprecated and a migration to 0.3.x is recommended

Apollo Client v3 -> apollo-link-scalars v2.x

The current Apollo Client v3 is used in the versions from 1.0

The 1.x family is considered deprecated and a migration to 2.x is recommended

Breaking Change: removing makeExecutableSchema

The versions that included makeExecutableSchema from graphql-tools are deprecated. This are the versions:

  • 0.1.x and 0.2.x => please migrate to 0.3.x (apollo client v2 line, deprecated)
  • 1.x => please migrate to 2.x (apollo client v3 line)

If you are not using makeExecutableSchema from this library, the upgrade will be transparent.

If you are using makeExecutableSchema, you just need to replace it from the version of graphql-tools compatible with the version of Apollo Client that you are using. Please have a look at the Example of loading a schema

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.

UPDATE: @woltob has a proposal related to this: #760

Installation

yarn add apollo-link-scalars graphql or npm install apollo-link-scalars graphql.

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, HttpLink } from "@apollo/client/core";
import { schema } from "./my-schema";

const link = ApolloLink.from([
  withScalars({ schema }),
  new HttpLink({ uri: "http://example.org/graphql" })
]);

// we can also pass a custom map of functions. These will have priority over the GraphQLTypes parsing and serializing functions from the Schema.
const typesMap = {
  CustomScalar: {
    serialize: (parsed: unknown): string | null => (parsed instanceof CustomScalar ? parsed.toString() : null),
    parseValue: (raw: unknown): CustomScalar | null => {
      if (!raw) return null; // if for some reason we want to treat empty string as null, for example
      if (isString(raw)) {
        return new CustomScalar(raw);
      }

      throw new Error("invalid value to parse")
    }
  }
};

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.
  • nullFunction (NullFunction, default null): by passing a set of transforms on how to box and unbox null types, you can automatically construct e.g. Maybe monads from the null types. See below for an example.
withScalars({
  schema,
  typesMap,
  validateEnums: true,
  removeTypenameFromInputs: true,
});

Example of loading a schema

import { gql } from "@apollo/client/core";
import { GraphQLScalarType, Kind } from "graphql";
import { makeExecutableSchema } from "@graphql-tools/schema";

// GraphQL Schema definition.
const typeDefs = gql`
  type Query {
    myList: [MyObject!]!
  }

  type MyObject {
    day: Date
    days: [Date]!
    nested: MyObject
  }

  "represents a Date with time"
  scalar Date
`;

const resolvers = {
  // example of scalar type, which will parse the string into a custom class CustomDate which receives a Date object
  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;
    },
  }),
};

// GraphQL Schema, required to use the link
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)
// note: sometimes it seems to be needed to cast it as Introspection Query
// `const schema = buildClientSchema((introspectionResult as unknown) as IntrospectionQuery)`

const scalarsLink = withScalars({
  schema,
  typesMap: { … },
});

Changing the behaviour of nullable types

By passing the nullFunctions parameter to withScalar, you can change the way that nullable types are handled. The default implementation will leave them exactly as is, i.e. null => null and value => value. If instead, you e.g. wish to transform nulls into a Maybe monad, you can supply functions corresponding to the following type. The examples below are based on the Maybe monad from Seidr but any implementation will do.

type NullFunctions = {
  serialize(input: any): any | null;
  parseValue(raw: any | null): any;
};

const nullFunctions: NullFunctions = {
  parseValue(raw: any) {
    if (isNone(raw)) {
      return Nothing();
    } else {
      return Just(raw);
    }
  },
  serialize(input: any) {
    return input.caseOf({
      Just(value) {
        return value;
      },
      Nothing() {
        return null;
      },
    });
  },
};

The nullFunctions are executed after the normal parsing/serializing. The normal parsing/serializing functions are not called for null values.

Both in parsing and serializing, we have the following logic (in pseudocode):

if (isNone(value)) {
  return this.nullFunctions.serialize(value);
}

const serialized = serializeNonNullValue(value);
return this.nullFunctions.serialize(serialized);
if (isNone(value)) {
  return this.nullFunctions.parseValue(value);
}

const parsed = parseNonNullValue(value);
return this.nullFunctions.parseValue(parsed);

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

#commit your changes:
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.

# bump package.json version, update CHANGELOG.md, git tag the release
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).

# Reset the repo to the latest commit and build everything
yarn run reset && yarn run test && yarn run doc:html

# Then version it with standard-version options. e.g.:
# don't bump package.json version
yarn run version -- --first-release

# Other popular options include:

# PGP sign it:
# $ yarn run version -- --sign

# alpha release:
# $ yarn run version -- --prerelease alpha

And after that, remember to publish the docs.

And finally push the new tags to Github and publish the package to npm.

# Push to git
git push --follow-tags origin master

# Publish to NPM (allowing public access, required if the package name is namespaced like `@somewhere/some-lib`)
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

# Prepare a standard release
yarn prepare-release

# Push to git
git push --follow-tags origin master

# Publish to NPM (allowing public access, required if the package name is namespaced like `@somewhere/some-lib`)
yarn publish --access public

Contributors ✨

Thanks goes to these wonderful people (emoji key):

Eduardo TuriΓ±o
Eduardo TuriΓ±o

πŸ€” πŸš‡ ⚠️ πŸ’» πŸ“–
Genadi Samokovarov
Genadi Samokovarov

πŸ› ⚠️ πŸ’»
JiΕ™Γ­ Brabec
JiΕ™Γ­ Brabec

πŸ“– πŸ› ⚠️ πŸ’» πŸ€”
Jakub Petriska
Jakub Petriska

πŸ›
Deyan Dobrinov
Deyan Dobrinov

πŸ› πŸ€”
Hugh Barrigan
Hugh Barrigan

⚠️ πŸ’» πŸ€”
Jeff Lau
Jeff Lau

πŸ“–
Florian CargoΓ«t
Florian CargoΓ«t

πŸ›
Jaff Parker
Jaff Parker

πŸ› πŸš‡
Kenneth
Kenneth

πŸ“–
Sir.Nathan (Jonathan Stassen)
Sir.Nathan (Jonathan Stassen)

πŸš‡ πŸ“¦

This project follows the all-contributors specification. Contributions of any kind welcome!

More Repositories

1

UMM-MAC-PathfinderWotR

UnityModManager changed files for Pathfinder Wrath of the Righteous for MacOS
11
star
2

KanbanizePHP

PHP Kanbanize API
PHP
2
star
3

ioredis-del-by-pattern.ts

ioredis util to delete keys by pattern on redis. Supports batches (pipeline) and lets the user decide to use `del` or `unlink` methods.
TypeScript
2
star
4

ts-key-set

(TypeScript port of https://github.com/eturino/ruby_key_set) KeySet with 4 classes to represent concepts of All, None, Some, and AllExceptSome, the last 2 with a sorted uniq list of keys, and all with intersection calculations
TypeScript
2
star
5

claims.py

Claim, ClaimSet and Ability for permissions (Python port of https://github.com/eturino/claims)
Python
1
star
6

html_surgeon

Ruby gem for surgical changes in HTML strings, using Nokogiri.
Ruby
1
star
7

PseudoArray

EtuDev PseudoArray lib for PHP, to be used in several Apps
PHP
1
star
8

feature_toggle_service

Service for using feature toggles in your ruby code (true/false by a specific key). It supports overrides, defaults, and it gets the information from etcd.
Ruby
1
star
9

Cookie

EtuDev lib Cookie helper for PHP
PHP
1
star
10

eapi

ruby gem for building complex structures that will end up in hashes and arrays.
Ruby
1
star
11

Calendar

EtuDev lib Calendar control for PHP with JS
JavaScript
1
star
12

ScriptManager

EtuDev base lib to load and execute external and internal Javascript using LAB.js
PHP
1
star
13

Cache

EtuDev Cache libs for PHP to be used in several apps. Provide a simple and common interface to multiple cache engines like Memcached or APC
PHP
1
star
14

Interfaces

EtuDev Interfaces common libs
PHP
1
star
15

DataGen

Data model classes generation for PHP apps: it generates Zend_Db Row and Table classes and a PseudoArray for each table in the database
PHP
1
star
16

Util

EtuDev PHP util libs, to be used in several apps
PHP
1
star
17

Data

EtuDev lib for Data manipulation in PHP, to be used in several apps.
PHP
1
star
18

Zend

EtuDev PHp classes to work with ZF1, to be used in several apps
PHP
1
star
19

i-claudius-subtitles

Subtitles for I Claudius (BBC)
1
star
20

Messages

EtuDev lib to handle flash messages from the PHP server to the browser using cookies and Javascript
JavaScript
1
star