Git Product home page Git Product logo

graphql-transform-scalars's Introduction

graphql-transform-scalars

Transform the response of your graphql request with mapper functions for your custom scalar types.

License npm version

Installation

Install with yarn or npm:

yarn add graphql-transform-scalars

or

npm install graphql-transform-scalars

Usage with graphql-request

With graphql-codegen

import { GraphQLClient } from 'graphql-request';
import fs from 'fs';
import { CalendarDate } from 'calendar-date';
import { getSdkWrapper, TransformCustomScalars } from 'graphql-transform-scalars';
import { getSdk } from './generated/graphql';

// Custom Scalar definition
const customScalarDefinitions = [
    {
        name: 'CalendarDate',
        parseValue: (val: unknown) => new CalendarDate(val as string),
    },
    {
        name: 'DateTime',
        parseValue: (val: unknown) => new Date(val as string),
    },
];

// The base schema is needed to get the Information about the graphql types returned from your request.
const schema = fs.readFileSync('path/to/your/schema.graphql', 'utf8');
const transformScalars = new TransformCustomScalars(schema, customScalarDefinitions);
const sdk = getSdk(new GraphQLClient('url'), getSdkWrapper(this.transformScalars));

You can directly pass your defined GraphQLScalarTypes to the TransformCustomScalars constructor. graphql-scalars has a lot of already pre-defined definitions you can use.

Example of a custom definition for the CalendarDate:
import { GraphQLError, GraphQLScalarType, Kind } from 'graphql';
import { CalendarDate } from 'calendar-date';

export const GraphQLCalendarDate: GraphQLScalarType = new GraphQLScalarType({
    name: 'CalendarDate',

    description:
    'A field representing a date without time information according to ISO 8601. E.g. "2020-01-01".',
    
    serialize(value: unknown) {
        if (value instanceof CalendarDate) {
            return value.toString();
        }
        if (typeof value === 'string') {
            try {
                const calendarDate = new CalendarDate(value);
                return calendarDate.toString();
            } catch (e) {
                throw new TypeError(
                    `Value of type string does not represent a valid calendar date: ${value}`,
                );
            }
        }
        throw new TypeError(`Value is not an instance of CalendarDate and not a string: ${value}`);
    },
    
    parseValue(value: unknown) {
        if (value instanceof CalendarDate) {
           return value;
        }
        if (typeof value === 'string') {
            try {
                return new CalendarDate(value);
            } catch (e) {
                throw new TypeError(
                    `Value of type string does not represent a valid calendar date: ${value}`,
                );
            }
        }
        throw new TypeError(`Value is not an instance of CalendarDate and not a string: ${value}`);
    },
    
    parseLiteral(ast) {
        if (ast.kind !== Kind.STRING) {
            throw new GraphQLError(`Can only validate strings as CalendarDates but got a: ${ast.kind}`);
        }
        try {
            return new CalendarDate(ast.value);
        } catch (e) {
            throw new TypeError(
                `Value of type string does not represent a valid calendar date: ${ast.kind}`,
            );
        }
    },
});

graphql-transform-scalars's People

Contributors

renovate[bot] avatar co-sic avatar semantic-release-bot avatar nodegin avatar

Stargazers

 avatar Dimitri Saplatkin avatar Thalles Passos avatar Tomas Fagerbekk avatar Pavel Shut avatar

Watchers

Peter Macherey avatar  avatar

Forkers

nodegin

graphql-transform-scalars's Issues

Parser and serializer?

Hi, I created a custom BigInt scalar which basically converts BigInt to string and vice-versa.

I'm using this lib to convert the string to BigInt in my client but is there a way to serialize the value when sending the request to the server (convert BigInt to string)?

Thanks for the great library!

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Awaiting Schedule

These updates are awaiting their schedule. Click on a checkbox to get an update now.

  • chore(deps): update devdependencies (non-major) to v7.12.0 (@typescript-eslint/eslint-plugin, @typescript-eslint/parser)

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/main.yml
  • actions/checkout v4
  • wagoid/commitlint-github-action v6
  • actions/checkout v4
  • actions/setup-node v4.0.2
  • actions/cache v4
  • actions/checkout v4
  • actions/setup-node v4.0.2
  • actions/cache v4
  • actions/checkout v4
  • actions/setup-node v4.0.2
  • actions/github-script v7.0.1
  • actions/github-script v7.0.1
.github/workflows/pr.yml
  • actions/checkout v4
  • wagoid/commitlint-github-action v6
  • amannn/action-semantic-pull-request v5.5.2
  • actions/checkout v4
  • actions/setup-node v4.0.2
  • actions/cache v4
  • actions/checkout v4
  • actions/setup-node v4.0.2
  • actions/cache v4
npm
package.json
  • @commitlint/cli 19.3.0
  • @commitlint/config-conventional 19.2.2
  • @graphql-codegen/add 5.0.2
  • @graphql-codegen/cli 5.0.2
  • @graphql-codegen/typescript 4.0.7
  • @graphql-codegen/typescript-graphql-request 6.2.0
  • @graphql-codegen/typescript-operations 4.2.1
  • @semantic-release/changelog 6.0.3
  • @semantic-release/git 10.0.1
  • @types/jest 29.5.12
  • @typescript-eslint/eslint-plugin 7.11.0
  • @typescript-eslint/parser 7.11.0
  • calendar-date 2.5.0
  • eslint 8.57.0
  • fast-check 3.19.0
  • graphql 16.8.1
  • graphql-request 6.1.0
  • husky 9.0.11
  • jest 29.7.0
  • lint-staged 15.2.5
  • prettier 3.3.0
  • rimraf 5.0.7
  • ts-jest 29.1.4
  • ts-node 10.9.2
  • typescript 5.4.5
  • graphql >=15

  • Check this box to trigger a request for Renovate to run again on this repository

How does the schema.graphql works?

Hello, I am facing some issue when using this library.
In the example there is a schema.graphql but I am not quite sure where this file is generated,
is it generated in the Backend? or generated by the graphql-codegen plugin?
I am using Nestjs as my backend so I tried to import the schema generated by autoSchemaFile config.
When it comes to custom scalar, it seem this library doesn't support scalars at all, or maybe I did something wrong.
Here is my schema.gql file in Backend side:

"""
A date-time string at UTC, such as 2007-12-03T10:15:30Z, compliant with the `date-time` format outlined in section 5.6 of the RFC 3339 profile of the ISO 8601 standard for representation of dates and times using the Gregorian calendar.
"""
scalar DateTime

type SomeEntity {
  createdAt: DateTime!
  id: Int!
}

By checking source code, it seem this library only process
if (n.kind === 'ObjectTypeDefinition' || n.kind === 'InterfaceTypeDefinition') {
where custom scalars kind is ScalarTypeDefinition.

Thank you for the library and any advice!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.