npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@bilgorajskim/ra-data-graphql

v2.1.0-2

Published

A GraphQL data provider for react-admin

Downloads

8

Readme

ra-data-graphql

A GraphQL data provider for react-admin built with Apollo

This is a very low level library which is not meant to be used directly unless you really want full control or are building a custom GraphQL data provider.

It provides the foundations for other GraphQL data provider packages such as ra-data-graphcool or ra-data-graphql-simple

About GraphQL and Apollo

This library is meant to be used with Apollo on the client side but you're free to use any graphql server.

Installation

Install with:

npm install --save graphql ra-data-graphql

or

yarn add graphql ra-data-graphql

Usage

// in App.js
import React, { Component } from 'react';
import buildGraphQLProvider from 'ra-data-graphql';
import { Admin, Resource, Delete } from 'react-admin';

import { PostCreate, PostEdit, PostList } from '../components/admin/posts';

const client = new ApolloClient();

class App extends Component {
    constructor() {
        super();
        this.state = { dataProvider: null };
    }
    componentDidMount() {
        buildGraphQLProvider()
            .then(dataProvider => this.setState({ dataProvider }));
    }

    render() {
        const { dataProvider } = this.state;

        if (!dataProvider) {
            return <div>Loading</div>;
        }

        return (
            <Admin dataProvider={dataProvider}>
                <Resource name="Post" list={PostList} edit={PostEdit} create={PostCreate} remove={Delete} />
            </Admin>
        );
    }
}

export default App;

Options

Customize the Apollo client

You can specify the client options by calling buildGraphQLProvider like this:

import { createNetworkInterface } from 'react-apollo';

buildGraphQLProvider({
    client: {
        networkInterface: createNetworkInterface({
            uri: 'http://api.myproduct.com/graphql',
        }),
    },
});

You can pass any options supported by the ApolloClient contructor with the addition of uri which can be specified so that we create the network interface for you.

You can also supply your own ApolloClient instance directly with:

buildGraphQLProvider({ client: myClient });

Introspection Options

Instead of running an IntrospectionQuery you can also provide the IntrospectionQuery result directly. This speeds up the initial rendering of the Admin component as it no longer has to wait for the introspection query request to resolve.

import { __schema as schema } from './schema';

const introspectionOptions = {
    schema
};

buildGraphQLProvider({
    introspection: introspectionOptions
});

The ./schema file is a schema.json in ./scr retrieved with get-graphql-schema --json <graphql_endpoint>.

Note: Importing the schema.json file will significantly increase the bundle size.

Specify your queries and mutations

For the provider to know how to map react-admin request to apollo queries and mutations, you must provide a queryBuilder option. The queryBuilder is a factory function which will be called with the introspection query result.

The introspection result is an object with 3 properties:

  • types: an array of all the GraphQL types discovered on your endpoint
  • queries: an array of all the GraphQL queries and mutations discovered on your endpoint
  • resources: an array of objects with a type property, which is the GraphQL type for this resource, and a property for each react-admin fetch verb for which we found a matching query or mutation

For example:

{
    types: [
        {
            name: 'Post',
            kind: 'OBJECT',
            fields: [
                { name: 'id', type: { kind: 'NON_NULL', ofType: { kind: 'SCALAR', name: 'ID' } } },
                { name: 'title', type: { kind: 'NON_NULL', ofType: { kind: 'SCALAR', name: 'String' } } },
                ...
            ]
        },
        ...
    ],
    queries: [
        {
            name: 'createPost',
            args: [
                { name: 'title', type: { kind: 'NON_NULL', ofType: { kind: 'SCALAR', name: 'String' } } }
            ],
            type : { kind: 'OBJECT', name: 'Category' }
        },
        ...
    ],
    resources: [
        {
            type: {
                name: 'Post',
                kind: 'OBJECT',
                fields: [
                    { name: 'id', type: { kind: 'NON_NULL', ofType: { kind: 'SCALAR', name: 'ID' } } },
                    { name: 'title', type: { kind: 'NON_NULL', ofType: { kind: 'SCALAR', name: 'String' } } },
                    ...
                ]
            },
            GET_LIST: {
                name: 'createPost',
                args: [
                    { name: 'title', type: { kind: 'NON_NULL', ofType: { kind: 'SCALAR', name: 'String' } } }
                ],
                type : { kind: 'OBJECT', name: 'Category' }
            },
            ...
        }
    ]
}

The queryBuilder function must return a function which will be called with the same parameters as the react-admin data provider but must return an object matching the options of the ApolloClient query method with an additional parseResponse function.

This parseResponse function will be called with an ApolloQueryResult and must returns the data expected by react-admin.

For example:

import buildFieldList from './buildFieldList';

const queryBuilder = introspectionResults => (raFetchType, resourceName, params) => {
    const resource = introspectionResults.resource.find(r => r.type.name === resourceName);

    switch (raFetchType) {
        case 'GET_ONE':
            return {
                query: gql`query ${resource[raFetchType].name}($id: ID) {
                    data: ${resource[raFetchType].name}(id: $id) {
                        ${buildFieldList(introspectionResults, resource, raFetchType)}
                    }
                }`,
                variables: params, // params = { id: ... }
                parseResponse: response => response.data,
            }
            break;
        // ... other types handled here
    }
}
buildGraphQLProvider({ queryBuilder });

Troubleshooting

When I create or edit a resource, the list or edit page does not refresh its data

react-admin maintain its own cache of resources data but, by default, so does the Apollo client. For every queries, we inject a default fetchPolicy set to network-only so that the Apollo client always refetch the data when requested.

Do not override this fetchPolicy.

Contributing

Run the tests with this command:

make test