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

ra-data-graphql-simple

v5.4.3

Published

A GraphQL simple data provider for react-admin

Downloads

10,901

Readme

ra-data-graphql-simple

A GraphQL data provider for react-admin built with Apollo and tailored to target a simple GraphQL implementation.

This is an example implementation to show how to build a graphql adapter using ra-data-graphql.

Installation

Install with:

npm install --save graphql ra-data-graphql-simple

or

yarn add graphql ra-data-graphql-simple

Usage

The ra-data-graphql-simple package exposes a single function, which is a constructor for a dataProvider based on a GraphQL endpoint. When executed, this function calls the GraphQL endpoint, running an introspection query. It uses the result of this query (the GraphQL schema) to automatically configure the dataProvider accordingly.

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

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

const dataProvider = buildGraphQLProvider({ buildQuery });

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

export default App;

Note: the parser will generate additional .id properties for relation based types. These properties should be used as sources for reference based fields and inputs like ReferenceField: <ReferenceField label="Author Name" source="author.id" reference="User">.

Expected GraphQL Schema

The ra-data-graphql-simple function works against GraphQL servers that respect a certain GraphQL grammar. For instance, to handle all the actions on a Post resource, the GraphQL endpoint should support the following schema:

type Query {
  Post(id: ID!): Post
  allPosts(page: Int, perPage: Int, sortField: String, sortOrder: String, filter: PostFilter): [Post]
  _allPostsMeta(page: Int, perPage: Int, sortField: String, sortOrder: String, filter: PostFilter): ListMetadata
}

type Mutation {
  createPost(
    title: String!
    views: Int!
    user_id: ID!
  ): Post
  updatePost(
    id: ID!
    title: String!
    views: Int!
    user_id: ID!
  ): Post
  updatePosts(
    ids: [ID!]
    data: PostBulkUpdatePayload
  ) : { ids: [ID!]}
  deletePost(id: ID!): Post
  deletePosts(ids: [ID!]) : { ids: [ID!]}
}

type Post {
    id: ID!
    title: String!
    views: Int!
    user_id: ID!
    User: User
    Comments: [Comment]
}

input PostFilter {
    q: String
    id: ID
    title: String
    views: Int
    views_lt: Int
    views_lte: Int
    views_gt: Int
    views_gte: Int
    user_id: ID
}

input PostBulkUpdatePayload {
    title: String
}

type ListMetadata {
    count: Int!
}

scalar Date

This is the grammar used e.g. by marmelab/json-graphql-server, a client-side GraphQL server used for test purposes.

Options

Customize the Apollo client

You can either supply the client options by calling buildGraphQLProvider like this:

buildGraphQLProvider({ clientOptions: { uri: 'http://localhost:4000', ...otherApolloOptions } });

Or supply your client directly with:

buildGraphQLProvider({ client: myClient });

Overriding a specific query

The default behavior might not be optimized especially when dealing with references. You can override a specific query by wrapping the buildQuery function:

// in src/dataProvider.js
import buildGraphQLProvider, { buildQuery } from 'ra-data-graphql-simple';

const myBuildQuery = introspection => (fetchType, resource, params) => {
    const builtQuery = buildQuery(introspection)(fetchType, resource, params);

    if (resource === 'Command' && fetchType === 'GET_ONE') {
        return {
            // Use the default query variables and parseResponse
            ...builtQuery,
            // Override the query
            query: gql`
                query Command($id: ID!) {
                    data: Command(id: $id) {
                        id
                        reference
                        customer {
                            id
                            firstName
                            lastName
                        }
                    }
                }`,
        };
    }

    return builtQuery;
};

export default buildGraphQLProvider({ buildQuery: myBuildQuery })

Customize the introspection

These are the default options for introspection:

const introspectionOptions = {
    include: [], // Either an array of types to include or a function which will be called for every type discovered through introspection
    exclude: [], // Either an array of types to exclude or a function which will be called for every type discovered through introspection
};

// Including types
const introspectionOptions = {
    include: ['Post', 'Comment'],
};

// Excluding types
const introspectionOptions = {
    exclude: ['CommandItem'],
};

// Including types with a function
const introspectionOptions = {
    include: type => ['Post', 'Comment'].includes(type.name),
};

// Including types with a function
const introspectionOptions = {
    exclude: type => !['Post', 'Comment'].includes(type.name),
};

Note: exclude and include are mutually exclusives and include will take precedence.

Note: When using functions, the type argument will be a type returned by the introspection query. Refer to the introspection documentation for more information.

Pass the introspection options to the buildApolloProvider function:

buildApolloProvider({ introspection: introspectionOptions });

Sparse Field Support for Queries and Mutations

By default, for every API call this data provider returns all top level fields in your GraphQL schema as well as association objects containing the association's ID. If you would like to implement sparse field support for your requests, you can request the specific fields you want in a request by passing them to the dataProvider via the available meta param. For example,

dataProvider.getOne(
    'posts',
    { 
        id, 
        meta: { 
            sparseFields: [
                'id', 
                'title', 
                { 
                    comments: [
                        'description', 
                        { 
                            author : [
                                'name', 
                                'email'
                            ]
                        }
                    ]
                }
            ]
        }
    },
);

This can increase efficiency, optimize client performance, improve security and reduce over-fetching. Also, it allows for the request of nested association fields beyond just their ID. It is available for all dataprovider actions.

DELETE_MANY and UPDATE_MANY Optimizations

Your GraphQL backend may not allow multiple deletions or updates in a single query. This provider defaults to simply making multiple requests to handle those. This is obviously not ideal but can be alleviated by supplying your own ApolloClient which could use the apollo-link-batch-http link if your GraphQL backend support query batching.

Contributing

Run the tests with this command:

make test