Options
All
  • Public
  • Public/Protected
  • All
Menu

Elide JSON API Client

npm npm gzip size code coverage maintainability build status styled with prettier All Contributors license

An opinionated {json:api} client for Elide based APIs

There are already a number of client libraries for working with JSON API, however this library is specifically designed for interacting with Elide based APIs, which has a few of it's own unique characteristics.

Features

  • Built with Typescript!
  • Built on top of axios as a peer dependency
  • Supports Promises and async/await
  • JSON API response normalization
    • Flatter structure
    • Merges included relationship data
  • Serializes normalized resources back to a JSON API structure
    • Dates are converted to Unix epoch time for Elide
    • Protected fields can be omitted from being sent to the API
  • Supports JSON Patch Extension for bulk writes and complex mutations
  • Parameter serialization
    • Fields, filter, include, sort
    • Pagination: size & number OR offset & limit
  • Request caching and throttling

Basic Usage

import ApiClient from 'elide-jsonapi-client'

// Initialize a new client
const api = new ApiClient({
  baseURL: 'http://localhost/api',
})

// Fetch a resource collection
const res = await api.fetch('articles')

// Create a resource
api.create('articles', {
  type: 'articles',
  title: 'Hello World',
})

// Update a resource
api.update('articles/1', {
  id: '1',
  type: 'articles',
  title: 'Hello World!!!',
})

// Remove a resource
api.remove('articles', 1)

Documentation

API Docs

Wiki

Credits

Inspired by Kitsu

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Ken White

⚠️ 💻

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

License

MIT

Index

Type aliases

Attribute

Attribute: string | number | boolean | object | undefined

Attribute of a Resource Object

ElideError

ElideError: { error: string; message: string; path: string; status: number; timestamp: string }

Errors

Type declaration

  • error: string
  • message: string
  • path: string
  • status: number
  • timestamp: string

NewResourceObject

NewResourceObject: { attributes?: Attributes; id?: undefined | string; links?: Links; relationships?: Relationships; type: string }

A representation of a new Resource Object that originates at the client and is yet to be created on the server. The main difference between a regular Resource Object is that this may not have an id yet.

Type declaration

  • Optional attributes?: Attributes
  • Optional id?: undefined | string
  • Optional links?: Links
  • Optional relationships?: Relationships
  • type: string

NormalizedResourceOrResources

NormalizedResourceOrResources: NormalizedResource | NormalizedResource[]

Operation

Operation: { op: OperationType; path: string; value: ResourceObject }

A Resource Operation

Type declaration

OperationType

OperationType: "add" | "remove" | "replace"

Operation Type constants

Operations

Operations: Operation[]

An array of Operations

PageParams

PageParams: { limit?: undefined | number; number?: undefined | number; offset?: undefined | number; size?: undefined | number; totals?: undefined | false | true }

Type declaration

  • Optional limit?: undefined | number
  • Optional number?: undefined | number
  • Optional offset?: undefined | number
  • Optional size?: undefined | number
  • Optional totals?: undefined | false | true

Params

Params: { fields?: string | Attributes; filter?: string | Attributes; include?: string | string[]; page?: undefined | number; pageSize?: undefined | number; sort?: string | string[] }

Parameters

Type declaration

  • Optional fields?: string | Attributes
  • Optional filter?: string | Attributes
  • Optional include?: string | string[]
  • Optional page?: undefined | number
  • Optional pageSize?: undefined | number
  • Optional sort?: string | string[]

RelationshipRef

RelationshipRef: { id: string; type: string }

Relationships

Type declaration

  • id: string
  • type: string

ResourceObject

ResourceObject: { attributes?: Attributes; id: string; links?: Links; relationships?: Relationships; type: string }

A representation of a single resource

Type declaration

ResourceObjectOrObjects

ResourceObjectOrObjects: ResourceObject | ResourceObjects

Either or a single Resource Object or an array of Resource Objects

ResourceObjects

ResourceObjects: ResourceObject[]

An array of Resource Objects

SerializeOptions

SerializeOptions: { dateAttrs?: string[]; idRequired?: undefined | false | true; protectedAttrs?: string[] }

Options

Type declaration

  • Optional dateAttrs?: string[]
  • Optional idRequired?: undefined | false | true
  • Optional protectedAttrs?: string[]

SerializeParamsOptions

SerializeParamsOptions: { prefix?: undefined | false | true; size?: undefined | number; totals?: undefined | false | true; type?: undefined | string }

Type declaration

  • Optional prefix?: undefined | false | true
  • Optional size?: undefined | number
  • Optional totals?: undefined | false | true
  • Optional type?: undefined | string

Variables

Const ID_REQUIRED

ID_REQUIRED: "Resource must have an `id` property" = "Resource must have an `id` property"

Const ID_TYPE_REQUIRED

ID_TYPE_REQUIRED: "Relationship resource must have `id` and `type` properties" = "Relationship resource must have `id` and `type` properties"

Const JSON_API_CONTENT_TYPE

JSON_API_CONTENT_TYPE: "application/vnd.api+json" = "application/vnd.api+json"

Const JSON_API_PATCH_CONTENT_TYPE

JSON_API_PATCH_CONTENT_TYPE: "application/vnd.api+json; ext=jsonpatch" = "application/vnd.api+json; ext=jsonpatch"

Const TYPE_REQUIRED

TYPE_REQUIRED: "Resource must have a `type` property" = "Resource must have a `type` property"

Functions

Const concatUnique

  • concatUnique(...arr: any[]): never[]
  • Merge arrays while preserving only unique items

    example

    concatUnique([1,2], [2,3])

    Parameters

    • Rest ...arr: any[]

      array of primitives

    Returns never[]

    array of unique items, e.g. [1,2,3]

deserialize

deserializeMutation

  • deserializeMutation(response: Response): (null | { id: string; type: string } | { errors: Error[] })[]
  • Deserializes a response from a JSON API PATCH request

    Parameters

    • response: Response

      A collection or response objects

    Returns (null | { id: string; type: string } | { errors: Error[] })[]

    A collection of normalized values

error

  • Destructures an Axios response error

    throws

    The mutated Error

    Parameters

    Returns void

extractRelationships

filterIncluded

  • filterIncluded(included: ResourceObject[], __namedParameters: { id: string; type: string }): { id: string; type: string } | { id: string; type: string } | { id: string; type: string } | { id: string; type: string }
  • Returns included relationship resources that match the provided relationship reference object

    Parameters

    • included: ResourceObject[]

      A collection of resource objects

    • __namedParameters: { id: string; type: string }
      • id: string
      • type: string

    Returns { id: string; type: string } | { id: string; type: string } | { id: string; type: string } | { id: string; type: string }

    A normalized resource object

isArray

  • isArray(value: any): value is any[]
  • Determines if a reference is an Array

    Parameters

    • value: any

      Reference to check

    Returns value is any[]

isDefined

  • isDefined(value: any): boolean
  • Determines if a reference is defined

    Parameters

    • value: any

      Reference to check

    Returns boolean

isObject

  • isObject(value: any): value is object
  • Determines if a reference is an 'Object'

    Parameters

    • value: any

      Reference to check

    Returns value is object

isPlainObject

  • isPlainObject(value: any): value is object
  • Determines if a reference is a plain Object. A "plain" object is typically created by {} or new Object(). Some types such as arrays and null, while technically objects, are not considered plain objects.

    Parameters

    • value: any

      Reference to check

    Returns value is object

linkRelationships

mapResources

normalizeCollection

normalizeResource

  • normalizeResource(resource: ResourceObject, included?: ResourceObject[]): { id: string; type: string } | { id: string; type: string } | { id: string; type: string } | { id: string; type: string }
  • Normalizes a resource by hoisting the attributes and linking relationships

    Parameters

    Returns { id: string; type: string } | { id: string; type: string } | { id: string; type: string } | { id: string; type: string }

    A normalized resource object

parseDate

  • parseDate(value: string): string | number
  • Converts a date string into Unix Epoch time

    Parameters

    • value: string

      A date string

    Returns string | number

    The time in milliseconds or the original value if it fails to parse

serialize

serializeMutation

serializeObject

  • serializeObject(obj: Attributes, param?: undefined | string): string
  • Recursively stringifies nested objects

    Parameters

    • obj: Attributes

      An object

    • Optional param: undefined | string

      The current query parameter

    Returns string

    A URI component

serializeParams

toQueryString

  • toQueryString(params: ParamsObject, prefix?: boolean): string
  • Constructs a URL query string for JSON API parameters

    Parameters

    • params: ParamsObject

      Parameters to parse

    • Default value prefix: boolean = false

      Prefix returned string with ? (default false)

    Returns string

    A URL query string

validateRelationship

validateResource

  • Throws if the provided resource doesn't have expected properties

    Parameters

    Returns void

Legend

  • Constructor
  • Property
  • Method
  • Property

Generated using TypeDoc