Skip to content

Used with Persisted Caching (JSON string from LocalStorage, AsyncStorage etc) #760

@woltob

Description

@woltob

Hi all,

if you want to revive your custom scalars from the persisted Cache (https://github.com/apollographql/apollo-cache-persist) (where it is saved as stringified JSON), you can use the JSON.parse function with a revive method.

I am using it as such:

import { DateTime } from 'luxon';

// Works for keys like createdAt, updatedAt and timestamp.
export const parseJsonWithDateTime = (
  jsonString: string,
  keyCheckFunctions: Array<(key: string) => boolean> = [
    (key) => key === 'timestamp',
    (key) => key.endsWith('At'),
  ],
) => {
  return JSON.parse(jsonString, (key, value) => {
    for (const keyCheckFunction of keyCheckFunctions) {
      if (keyCheckFunction(key)) {
        return DateTime.fromISO(value);
      }
    }
  });
};

To enable custom scalar type generation with the newest apollo codegen, you can use the following setup for codegen.yml

I am not so sure about the two options here
passthroughCustomScalars: true and customScalarFormat: 'passthrough' but they don't break it.

hooks:
  afterAllFileWrite:
    - prettier --write
overwrite: true
schema: 'graphql.schema.json'
documents: 'src/**/*.{tsx,ts}'
config:
  scalars:
    DateTime: DateTime
    JSONObject: JSONObject
generates:
  src/generated-graphql-types.tsx:
    plugins:
      - 'typescript'
      - 'typescript-operations'
      - 'typescript-react-apollo'
      - 'named-operations-object'
    config:
      namingConvention:
        default: 'no-change-case'
        enumValues: 'keep'
      passthroughCustomScalars: true
      customScalarFormat: 'passthrough'
      withComponent: false
      withHOC: true
  ./src/generated-graphql-fragment-matcher.ts:
    plugins:
      - fragment-matcher
    config:
      namingConvention:
        default: 'no-change-case'
        enumValues: 'keep'
      passthroughCustomScalars: true
      customScalarFormat: 'passthrough'
  ./graphql.schema.json:
    plugins:
      - 'introspection'
    config:
      passthroughCustomScalars: true
      customScalarFormat: 'passthrough'
      namingConvention:
        default: 'no-change-case'
        enumValues: 'keep'

Hope it helps someone.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions