Git Product home page Git Product logo

fetch's Introduction

wp-headless

drone Coverage Status npm Bundle size

Fetch (alpha)

A Wordpress API client that works both in the browser and in Node. Tiny footprint, > 95% code coverage, browser tested down to IE11, tree shakable CJS and ES6 builds, expressive syntax.

Installation

The architecture of Fetch allows you to specify your own transport layer such as fetch or axios. (read more)

Yarn

yarn add @wp-headless/client @wp-headless/transport-fetch

NPM

npm install @wp-headless/client @wp-headless/transport-fetch

Usage

Creating a client instance bound to the endpoint of your Wordpress install:

import Client from '@wp-headless/client';
import FetchTransport from '@wp-headless/transport-fetch';

const client = new Client({
  endpoint: 'https://demo.wp-api.org/wp-json',
  transport: new FetchTransport()
});

You may also use another transport layer such as axios:

import Client from '@wp-headless/client';
import AxiosTransport from '@wp-headless/transport-axios';

const client = new Client({
  endpoint: 'https://demo.wp-api.org/wp-json',
  transport: new AxiosTransport()
});

Fetching posts using async await:

const posts = await client.posts().get();

Or with promises:

client.posts().get().then(posts => {
  console.log(posts);
});

Resources

Client instances provide the following API resource methods:

  • client.categories()
  • client.comments()
  • client.media()
  • client.statuses()
  • client.posts()
  • client.pages()
  • client.settings()
  • client.tags()
  • client.taxonomies()
  • client.types()
  • client.users()

These resource methods are simply syntax sugar for setting the path and namespace to an API resource. Therefore the following are equivalent:

const post = await client.posts().get(1);
const post = await client.get('posts/1');

Adding custom request methods is easy (example WooCommerce REST API), the following would fetch the enpoint http://demo.wp-api.org/wp-json/wc/v2/products:

client.products = () => client.namespace('wc/v2').resource('products');

const products = await client.products().get();

Of course you could simply also do the following:

const dogBone = await client.namespace('wc/v2').get('products/123');

Methods

Client instances also provide access to HTTP methods to access API resources.

client.get(); // Http GET
client.create(); // Http POST
client.update(); // Http PATCH
client.delete(); // Http DELETE

Params

You can pass request parameters as an object to any of the above methods:

const post = client.posts().create({ 
  title: 'Hello World!', 
  content: 'Lorem ipsum dolor sit amet...',
  excerpt: 'Etiam at feugiat neque...'
});

You may write parameters as camel case or snake case:

const post = client.posts().create({ perPage: 10 });

const posts = client.posts().get({ per_page: 10 });

Its also possible to set global params that will be sent with each request:

// Sets single param key/value
client.param('source', 'wp-headless');

// Merges object with current global param values
client.param({
  source: 'wp-headless',
  perPage: 15,
  orderby: 'title'
});

To retrieve global params:

// Single value
client.param('source'); // wp-headless

// All values
client.params;

Embed data

WordPress API supports embedding of resources and instead of having to provide _embed=true as a param on every request you can simpley use embed() before any request methods.

More about WordPress API embedding can you read here.

const posts = await client.posts().embed().get({
  slug: 'hello-world'
});

File uploading

When Uploading a file you can use client.file(file, [name]) to specify a file or a file buffer to attach to the request with a name (optional).

In the browser:

const file = document.getElementById('upload-input').files[0];

const upload = await client.media().file(file, 'Puppy Dog').create({
  title: 'Puppy dog with a bone'
});

In Node:

const file = fs.createReadStream('test.jpg');

client.media().file(file, 'Puppy Dog').create({
  title: 'Puppy dog with a bone'
});

Transport Layers

The architecture of Fetch allows you to specify your own transport layer such as fetch or axios. This allows devs to use a library that they are familiar with, and perhaps are already using in their app, saving bundle size.

Fetch

The fetch transport layer uses the Fetch API Standard to make requests. This is supported in all modern browsers and newer versions of Node. This is what our team uses.

To support older browsers you will have to implement a polyfill such as isomorphic-fetch or (isomorphic-unfetch)[https://github.com/developit/unfetch/tree/master/packages/isomorphic-unfetch]:

yarn add @wp-headless/client @wp-headless/transport-fetch isomorphic-unfetch
import 'isomorphic-unfetch';
import Client from '@wp-headless/client';
import FetchTransport from '@wp-headless/transport-fetch';

const client = new Client({
  endpoint: 'https://demo.wp-api.org/wp-json',
  transport: new FetchTransport()
});

Axios

Axios is a popular HTTP request package that is usable in Node and the browser, no polyfill is needed. Although it does have a larger bundle size:

import Client from '@wp-headless/client';
import AxiosTransport from '@wp-headless/transport-axios';

const client = new Client({
  endpoint: 'https://demo.wp-api.org/wp-json',
  transport: new AxiosTransport()
});

Others

We endevour to release other transport layers for superagent and ky in the future. We would love community contributions!

Thanks

BrowserStack Logo

Thanks to BrowserStack for lending us their amazing infrastructure to give us automated browser coverage

fetch's People

Contributors

andrewmclagan 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.