Git Product home page Git Product logo

graphql-lodash's Introduction

GraphQL Lodash logo

GraphQL Lodash

npm David David npm

Unleash the power of lodash inside your GraphQL queries

Table of contents

Why?

GraphQL allows to ask for what you need and get exactly that. But what about the shape? GraphQL Lodash gives you the power of lodash right inside your GraphQL Query using @_ directive.

lodash usage gif

Note: This is an experimental project created to explore the concept of Query and transformation collocation.

We encourage you to try it inside our demo or check detailed walkthrough.

Example queries

Here are a few query examples you can run against StartWars API:

Find the planet with the biggest population

Find the planet with the biggest population

Get gender statistics

Get gender statistics

Map characters to films they are featured in

Map characters to films they are featured in

Install

npm install --save graphql-lodash

or

yarn add graphql-lodash

API

graphqlLodash(query, [operationName])

  • query (required) - query string or query AST
  • operationName (optional) - required only if the query contains multiple operations

Returns

{
  query: string|object,
  transform: Function
}
  • query - the original query with stripped @_ directives
  • transform - function that recieves response.data as a single argument and returns the same data in the intended shape.

Usage Examples

The simplest way to integrate graphql-lodash is to write wrapper function for graphql client of you choice:

import { graphqlLodash } from 'graphql-lodash';

function lodashQuery(queryWithLodash) {
  let { query, transform } = graphqlLodash(queryWithLodash);
  // Make a GraphQL call using 'query' variable as a query
  // And place result in 'result' variable
  ...
  result.data = transform(result.data);
  return result;
}

Fetch example

An example of a simple client based on fetch API:

function executeGraphQLQuery(url, query) {
  return fetch(url, {
    method: 'POST',
    headers: new Headers({"content-type": 'application/json'}),
    body: JSON.stringify({ query: query })
  }).then(response => {
    if (response.ok)
      return response.json();
    return response.text().then(body => {
      throw Error(response.status + ' ' + response.statusText + '\n' + body);
    });
  });
}

function lodashQuery(url, queryWithLodash) {
  let { query, transform } = window.GQLLodash.graphqlLodash(queryWithLodash);
  return executeGraphQLQuery(url, query).then(result => {
    result.data = transform(result.data);
    return result;
  });
}

// then use as bellow
lodashQuery('https://swapi.apis.guru', `{
  planetWithMaxPopulation: allPlanets @_(get: "planets") {
    planets @_(maxBy: "population") {
      name
      population
    }
  }
}`).then(result => console.log(result.data));

Caching clients

For caching clients like Relay and Apollo we recommend to apply the transformation after the caching layer. Here is proposed solution for Relay:

Relay usage

We are still figuring out how to do this and any feedback is welcome.

Usage with react-apollo

When using with Apollo you can use props option to apply transformations:

const rawQuery = gql`
  # query with @_ directives
`;

const {query, transform} = graphqlLodash(rawQuery);
export default graphql(query, {
  props: (props) => ({...props, rawData: props.data, data: transform(props.data)})
})(Component);

You can write a simple wrapper for simplicity:

import { graphql } from 'react-apollo';
import { graphqlLodash } from 'graphql-lodash';

export function gqlLodash(rawQuery, config) {
  const {query, transform} = graphqlLodash(rawQuery);
  let origProps = (config && config.props) || ((props) => props);

  return (comp) => graphql(query, {...config,
    props: (props) => origProps({
      ...props,
      rawData: props.data,
      data: transform(props.data)
    })
  })(comp);
}
// then use as bellow
export default gqlLodash(query)(Component);

Just replace graphql with gqlLodash and you are ready to use lodash in your queries. Check out react-apollo-lodash-demo repo.

Usage on server side

In theory, this tool can be used on the server. But this will break the contract and, most likely, will break all the GraphQL tooling you use. Use it on server-side only if you know what you do.

graphql-lodash's People

Contributors

ivangoncharov avatar mattleff avatar nisaacson avatar romanhotsiy avatar vedmalex avatar

Watchers

 avatar  avatar

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.