@system76/js-api

JavaScript fetch wrapper for Elixir Phoenix APIs
1,036 5
Install
npm install @system76/js-api
Latest Version:2.3.0
License:GPL-3.0
Last Updated:Jan 7, 2023
Links: GitHub  ·  npm
Maintainer: system76

This package is a simple wrapper around fetch to make it easier to interact with Elixir Phoenix APIs. It is rather opinionated to System76 projects, but may be useful for other projects.

While this package can be used in any JS project, it is designed with Vue (and Nuxt.JS) specifically in mind.

Using

Regular JS

npm install --save @system76/js-api
import { Client } from '@system76/js-api'

const api = () => new Client({
  baseUrl: 'https://api-v2.system76.com',
  token: () => 'testingtoken'
})

const { data } = await api().get('/catalog/products').jsonApi()

Nuxt

Add these fields to your nuxt.config.js file:

export default {
  plugins: [
    `~/plugins/api`
  ]
}

Put this in your ~/plugins/api.js:

import { Client } from '@system76/js-api'

export default function (ctx, inject) {
  const api = () => new Client({
    baseUrl: 'https://api-v2.system76.com',
    token: () => `Token ${ctx.store.getters.token}`
  })

  inject('api', () => api())
}

Then you can use $api in the nuxt context. For instance, in a component you can do:

export default {
  asyncData: async ({ $api }) => ({
    products: await $api().get('/catalog/products').jsonApi().flatten()
  })
}

or:

export default {
  methods: {
    async create () {
      const { data: products } = await $api().get('/catalog/products')
        .jsonApi()
        .page(2)
    }
  }
}

Client

This is your main client used for making requests. All methods return the client again, so it's easily chainable.

// Adds an include statement to the request. Useful for JSON API endpoints
client.include('products.options.components')

// Adds a header to the request
client.header('Accept', 'application/json')

// Adds an authentication header
client.authentication('token abc123')

// Adds a parameter to the URL
client.parameter('filter[status]', 'awesome')

// Adds pagination page parameter
client.page(1)

// Adds pagination page size parameter
client.size(100)

// Adds a no cache or cache header to the request (defaults to true)
client.cache()
client.cache(false)

// Adds JSON API headers and changes the request form a bit to match
client.jsonApi()

// Adds body data to the request. Does not work with HEAD or GET requests. Gets
// JSON.stringify-ed
client.body({ data: { attributes: { key: 'value' }}})

// Sets the method and path for the request.
client.get('/products')
client.post('/products')
client.patch('/products')
client.put('/products')
client.delete('/products/2')

// Makes the return value of the request _just_ the body data. This is similar
// to doing `(await client.get()).body` but less verbose
client.flatten()

ApiError

This is the error thrown if the response is not ok. It has a bunch of helpers to assist in parsing the error data.

// Mapped for use in Nuxt. If the API returns a 500, your app returns a 500
error.status // 500
error.statusCode // 500

// A simple array of error data found
error.errors // ['Not authorized']
error.errors // ['email has already been taken']

// An object of validation errors from the server
error.fields.email // ['has already been taken']
error.fields.password // null

Development

  1. Download the repository

  2. Run npm ci

  3. Start hacking

  4. Run npm test to make sure you didn't break anything

  5. Submit a PR!

Deployment

To trigger a release, push a commit to the master branch in the Angular Commit Message Conventions format.

Related Packages

@meathill/digest-fetch

A tiny fetch wrapper to add digest auth support, without any dependencies.

240
nuxt-api-party

Auto-generated composables for any API, typed from OpenAPI and never exposing yo...

246,965 306
nuxt-authentication

Nuxt Authentication is a simple module that proposes authentication functionalit...

2,371 0
@x-app/nuxt-api

Configurable API composable for Nuxt 3 and Nuxt 4

393
nuxt-open-fetch

Generate zero-overhead, 100% typed OpenAPI clients for Nuxt.

379,588 259

Version History

Version Released License
2.3.0 GPL-3.0
2.2.0 GPL-3.0
2.1.2 GPL-3.0
2.1.1 GPL-3.0
2.1.0 GPL-3.0