0.3.1 • Published 5 years ago

wasp-graphql-next v0.3.1

Weekly downloads
1
License
MIT
Repository
github
Last release
5 years ago

🐝 wasp-graphql 🐝

npm Build Status npm bundle size (minified) code style: prettier

contributions welcome All Contributors GitHub

Queries a GraphQL endpoint with syntax similar to a fetch request. Accepts a url and a settings object, and returns a Promise that can resolve the request.

Promise and fetch must either be in scope, or passed in as a third argument part.

No additional dependencies are installed.

Fully compatible with RESTful APIs.

Useful Links

Table of Contents

Quick Usage

MDN Documentation: Using Fetch

wasp-graphql strives to match the Fetch API as closely as possible.

/* Installation */
npm install --save wasp-graphql
/* Imports */
import { query } from 'wasp-graphql';
/**
 * Syntax: query(url, init, customEnv)
 *
 * @param {string} url - The url for the intended resource
 * @param {(string|Object)} init - Can be a string of fields or a configuration object for fetch
 * @param {Object} customEnv - Custom functions for required functionality (e.g., "fetch")

 * @returns {Promise}
 */

const myUrl = '/api/my-custom-resource'
const myHeaders = { 'Content-Type': 'application/json' }

// #1 argument: The url for the intended resource
query(myUrl)

// #2 argument: Object properties for configuring the request
query(myUrl, {
  headers: myHeaders,
  body: JSON.stringify(query: '{foo { bar }}') // Fully specified request body
})
query(myUrl, {
  headers: myHeaders,
  query: '{foo { bar }}' // Query shortcut for specifying the body property
})
query(myUrl, {
  headers: myHeaders,
  fields: '{foo { bar }}' // Query shortcut for specifying the body property (alternate name for query)
})
query(myUrl, '{foo { bar }}') // An even shorter shortcut for when no custom request properties are required

// #3 argument (rare)
// Only necessary if fetch or Promise is not in scope.
//    Use this argument to pass in custom versions.
query('/myurl', '{foo { bar }}', {
  Promise: () => {/* my custom Promise functionality */}),
  fetch: () => {/* my custom fetch functionality */}),
})
/* Usage example */
import { query } from 'wasp-graphql';

const url = '/api/my-custom-resource';
const init = {
  headers: { 'Content-Type': 'application/json' },
  query: '{foo { bar }}'
};

const myResults = query(url, init)
  .then(res => res.json())
  .then(json => console.log(json));

See How It Works for additional usage examples.

Compatibility

  • Tested against Node.js v6+ (including latest version)
  • Requires fetch to be either saved to the global scope or passed in as a configuration parameter

Fetch as Global/Fetch API

(Do I have it/Can I Use It?)

TODO

Ways to install fetch:

Fetch as Parameter

See Configuration Parameters

TODO

Usage Guide

Installation

Install via npm:

// npm
npm install --save wasp-graphql

// yarn
yarn add wasp-graphql

How to Import

// ES5
var Wasp = require('wasp-graphql');
var query = Wasp.query;

// ES6
import Wasp from 'wasp-graphql';
const query = Wasp.query;

// ES6 + Object Destructuring
import { query } from 'wasp-graphql';

How It Works

Making a request

wasp-graphql

**Making a

How to query a GraphQL server.

Write a string to request data ("fields") from a GraphQL endpoint.

Given an example string:

var myFields = `{
  hero {
    name
    friends {
      name
    }
  }
}`;

Pass the query string alone as the second argument...

import { query } from 'wasp-graphql';
query('/my/url/endpoint', myFields);

Or as a property called fields for the second argument...

import { query } from 'wasp-graphql';

query('/my/url/endpoint', { fields: myFields });
// Any `fetch` init property can be included as well
query('/my/url/endpoint', { fields: myFields, mode: 'no-cors' });

Or as part of a fully customized body property (ADVANCED).

import { query } from 'wasp-graphql';

// Remember that `body` must be a JSON parsable string. Also, many GQL
//    servers will expect fields to be sent under a `body.query` property.
const init = {
  body: JSON.stringify({
    query: myFields
  }),
  credentials: 'include'
};
query('/my/url/endpoint', init);

Then, you can unpack the results of query with .json():

import { query } from 'wasp-graphql';

query('/my/url/endpoint', init)
  .then(response => {
    console.log(response.json()); // my data
  })
  .catch(error => {
    console.log(error); // my error
  });

As a thin wrapper over the Fetch API, anything that applies to fetch will also apply to query as well.

Variables

About dynamic arguments

GraphQL variables can be passed on as a separate property named variables.

import { query } from 'wasp-graphql';

query(url, { fields: myFields, variables: myVariables });

A longer example:

import { query } from 'wasp-graphql';

const url = '/api/starwars';
const fields = `
  query HeroNameAndFriends($episode: Episode) {
    hero(episode: $episode) {
      name
      friends {
        name
      }
    }
  }
`;
const variables = {
  episode: 'JEDI'
};

query(url, { fields, variables })
  .then(res => res.json())
  .then(json => {
    console.log(json);
  });

// A custom body property can be used as well
query(url, { body: JSON.stringify({ fields, variables }) }).then(/* ... */);

Examples of good SYNTAX

import { query } from 'wasp-graphql'

// fields as a second argument
query('/foo/bar', '{foo { bar baz }}')  // good

// extended fields as a second argument
query('/myendpoint', 'query myQuery { field1 field2 { subfield1 } }')  // good

// with a fields as a property and the default settings
query('/myurl', { fields: '{foo { bar }}' })  // good

// with a fields as a property and custom fetch options
const config = {
  fields: 'query FooBarBaz {foo bar baz}',
  cache: 'no-cache',
  mode: "same-origin"
}
query('/myurl', config)  // good

// Remember that `body` must be a JSON parsable string. Also, many GQL
//    servers will expect fields to be sent under a `body.query` property.
//    GQL variables can be sent under `body.variables`.
const init = {
  body: JSON.stringify({
    query: myFields,
    variables: '{ "name": "Batman" }'
  }),
  credentials: 'include',
  mode: 'same-origin'
}
query('/my/url/endpoint', init)  // good

// With a fully custom init object.  Body must be a JSON parsable string
//    with a query property.
const init = {
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  }
  body: JSON.stringify({
    query: myFields,
    variables: '{ "name": "Batman" }'
  }),
  credentials: 'include',
  mode: 'same-origin'
}
query('/my/url/endpoint', init)  // good

Important note: If you add your own headers to the init object, the default headers will be overwritten. If this causes an issue, including these with your custom headers should resolve it:

{
  'Content-Type': 'application/json',
  'Accept': 'application/json'
}

Examples of broken SYNTAX

// No arguments
query(); // bad

// No second argument
query('/foo/bar'); // bad

// An invalid second argument
query('/foo/bar', []); // bad

// Empty strings
query('', ''); // bad

// Misconfigured init object (missing a body property)
query('/foo', { cache: 'no-cache' }); // bad

// Misconfigured body property (did not use JSON.stringify())
query('/foo', { body: { query: '{foo bar}' } }); // bad

// if the first argument isn't an endpoint, nothing is fetched
query('I AM NOT A URL', '{ foo bar baz }'); // bad

// if the second argument is a string, but not a valid query string,
//      then the server won't be able to do anything with it
query('/foo', 'I AM NOT A STRING OF GRAPHQL FIELDS'); // bad

Library API

Quick Reference

import { query, mutation } from 'wasp-graphql';

query(url: string, init: string | Object)

/**
 * Provides a thin, GQL-compliant wrapper over the Fetch API.
 *
 * SYNTAX: query(url, init)

 * @param {string} url - The url for the intended resource
 * @param {(string|Object)} init - Can be a string of fields or a configuration object
 * @param {string} [init.fields] - GQL fields: Will be added to the body of the request
 * @param {Object} [init.variables] - GQL variables: Will be added to the body of the request
 * // For additional valid arguments, see the Fetch API:
 * // https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
 *
 * Default init properties
 * @param {string} [init.method='POST']
 * @param {Object} [init.headers={ 'Content-Type': 'application/json', 'Accept': 'application/json' }]
 *
 * @returns {Promise}
 */

import { query } from 'wasp-graphql';

mutation(url: string, init: string | Object)

Alias for query.


Changelog

View it here

Contributing

Read more

Contributors

Thanks goes to these wonderful people:

Contributors

Thanks goes to these wonderful people:

This project follows the all-contributors specification. Contributions of any kind welcome!

Code of Conduct

Read our Code of Conduct here.

License

Free and Open Source under the MIT License.

0.3.1

5 years ago

0.3.0

5 years ago