Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

rapiq

Tada5hi221kMIT0.9.0TypeScript support: included

A tiny library which provides utility types/functions for request and response query handling.

query, json, json-api, api, rest, api-utils, include, pagination, sort, fields, filter, relations, typescript

readme

rapiq 🌈

npm version main codecov Known Vulnerabilities semantic-release: angular

Rapiq (R*est *Api Q*uery) is a library to build an efficient interface between client- & server-side applications. It defines a scheme for the request, but *not for the response.

Table of Contents

Installation

npm install rapiq --save

Documentation

To read the docs, visit https://rapiq.tada5hi.net

Parameters

  • fields
    • Description: Return only specific resource fields or extend the default selection.
    • URL-Parameter: fields
  • filters
    • Description: Filter the resources, according to specific criteria.
    • URL-Parameter: filter
  • relations
    • Description: Include related resources of the primary resource.
    • URL-Parameter: include
  • pagination
    • Description: Limit the number of resources returned from the entire collection.
    • URL-Parameter: page
  • sort
    • Description: Sort the resources according to one or more keys in asc/desc direction.
    • URL-Parameter: sort

It is based on the JSON-API specification.

Usage

This is a small outlook on how to use the library. For detailed explanations and extended examples, read the docs.

Build 🔧

The first step is to construct a BuildInput object for a generic Record <T>. Pass the object to the buildQuery method to convert it to a transportable string.

The BuildInput<T> can contain a configuration for each Parameter/ URLParameter.

NOTE: Check out the API-Reference of each parameter for acceptable input formats and examples.

After building, the string can be passed to a backend application as http query string argument. The backend application can process the request, by parsing the query string.

Example

The following example is based on the assumption, that the following packages are installed:

It should give an insight on how to use this library. Therefore, a type which will represent a User and a method getAPIUsers are defined. The method should perform a request to the resource API to receive a collection of entities.

import axios from "axios";
import {
    buildQuery,
    BuildInput
} from "rapiq";

export type Realm = {
    id: string,
    name: string,
    description: string,
}

export type Item = {
    id: string,
    realm: Realm,
    user: User
}

export type User = {
    id: number,
    name: string,
    email: string,
    age: number,
    realm: Realm,
    items: Item[]
}

type ResponsePayload = {
    data: User[],
    meta: {
        limit: number,
        offset: number,
        total: number
    }
}

const record: BuildInput<User> = {
    pagination: {
        limit: 20,
        offset: 10
    },
    filters: {
        id: 1
    },
    fields: ['id', 'name'],
    sort: '-id',
    relations: ['realm']
};

const query = buildQuery(record);
// console.log(query);
// ?filter[id]=1&fields=id,name&page[limit]=20&page[offset]=10&sort=-id&include=realm

async function getAPIUsers(
    record: BuildInput<User>
): Promise<ResponsePayload> {
    const response = await axios.get('users' + buildQuery(record));

    return response.data;
}

(async () => {
    let response = await getAPIUsers(record);

    // do something with the response :)
})();

The next section will describe, how to parse the query string on the backend side.

Parse 🔎

The last step of the whole process is to parse the transpiled query string, to an efficient data structure. The result object (ParseOutput) can contain an output for each Parameter/ URLParameter.

NOTE: Check out the API-Reference of each parameter for output formats and examples.

Example

The following example is based on the assumption, that the following packages are installed:

For explanation purposes, three simple entities with relations between them are declared to demonstrate the usage on the backend side.

entities.ts

import {
    Entity,
    PrimaryGeneratedColumn,
    Column,
    OneToMany,
    JoinColumn,
    ManyToOne
} from "typeorm";

@Entity()
export class User {
    @PrimaryGeneratedColumn({unsigned: true})
    id: number;

    @Column({type: 'varchar', length: 30})
    @Index({unique: true})
    name: string;

    @Column({type: 'varchar', length: 255, default: null, nullable: true})
    email: string;

    @Column({type: 'int', nullable: true})
    age: number

    @ManyToOne(() => Realm, { onDelete: 'CASCADE' })
    realm: Realm;

    @OneToMany(() => User, { onDelete: 'CASCADE' })
    items: Item[];
}

@Entity()
export class Realm {
    @PrimaryColumn({ type: 'varchar', length: 36 })
    id: string;

    @Column({ type: 'varchar', length: 128, unique: true })
    name: string;

    @Column({ type: 'text', nullable: true, default: null })
    description: string | null;
}

@Entity()
export class Item {
    @PrimaryGeneratedColumn({unsigned: true})
    id: number;

    @ManyToOne(() => Realm, { onDelete: 'CASCADE' })
    realm: Realm;

    @ManyToOne(() => User, { onDelete: 'CASCADE' })
    user: User;
}
import { Request, Response } from 'express';

import {
    applyQuery,
    useDataSource
} from 'typeorm-extension';

/**
 * Get many users.
 *
 * Request example
 * - url: /users?page[limit]=10&page[offset]=0&include=realm&filter[id]=1&fields=id,name
 *
 * @param req
 * @param res
 */
export async function getUsers(req: Request, res: Response) {
    const dataSource = await useDataSource();
    const repository = dataSource.getRepository(User);
    const query = repository.createQueryBuilder('user');

    // -----------------------------------------------------

    // parse and apply data on the db query.
    const { pagination } = applyQuery(query, req.query, {
        defaultPath: 'user',
        fields: {
            allowed: ['id', 'name', 'realm.id', 'realm.name'],
        },
        filters: {
            allowed: ['id', 'name', 'realm.id'],
        },
        relations: {
            allowed: ['items', 'realm']
        },
        pagination: {
            maxLimit: 20
        },
        sort: {
            allowed: ['id', 'name', 'realm.id'],
        }
    });

    // -----------------------------------------------------

    const [entities, total] = await query.getManyAndCount();

    return res.json({
        data: {
            data: entities,
            meta: {
                total,
                ...pagination
            }
        }
    });
}

License

Made with 💚

Published under MIT License.

changelog

0.9.0 (2023-07-04)

Bug Fixes

  • refactoring bug of throwOnFailure option (a555b2d)

Features

  • allow throwing error on invalid parsing input (#312) (3afd7f2)

0.8.1 (2023-05-29)

Bug Fixes

  • apply defaults if parse input has no parameter keys (c4ba303)
  • deps: bump smob to v1.x (978da3a)
  • simplify build query string util (7e7eb28)
  • use custom merger for parameters (4ff0ca5)

0.8.0 (2023-02-14)

Features

  • enhance parsing of parameters (2cc8b4d)

0.7.0 (2023-01-27)

Features

  • refactor build pipeline & replaced babel with swc (a3dcc53)

0.6.6 (2023-01-18)

Bug Fixes

  • avoid nullish coalescing operator (2f98bc1)

0.6.5 (2023-01-18)

Bug Fixes

  • removed minimatch + replaced babel with esbuild for transpiling (3b6744d)

0.6.4 (2023-01-17)

Bug Fixes

  • deps: bump minimatch from 5.1.2 to 6.0.4 (6113e42)
  • deps: bump smob from 0.0.6 to 0.0.7 (40ae989)

0.6.3 (2023-01-04)

Bug Fixes

  • deps: bump json5 from 1.0.1 to 1.0.2 (dfede3d)

0.6.2 (2022-12-22)

Bug Fixes

  • deps: bump minimatch from 5.1.1 to 5.1.2 (6c3cf63)

0.6.1 (2022-11-30)

Bug Fixes

  • deps: bump minimatch from 5.1.0 to 5.1.1 (d1e3852)

0.6.0 (2022-11-28)

Features

0.5.0 (2022-11-27)

Features

  • allow null value in filter list (a264d6c)

0.4.1 (2022-10-28)

Bug Fixes

  • allow enable/disable parameter parsing by boolean for parseQuery (2b29f41)

0.4.0 (2022-10-28)

Bug Fixes

  • allow non matching regex strings, if permitted by options (145b119)

Features

  • parse everything, if allowed- & default- option are not defined (9bda36a)

0.3.2 (2022-10-27)

Bug Fixes

  • only inherit default-path for defined options (454b54a)

0.3.1 (2022-10-22)

Bug Fixes

  • cleanup types + support more filter input values (1c0e59f)

0.3.0 (2022-10-21)

Bug Fixes

  • changed structure of filters-parse-output-element (0f3ec4e)
  • filter-value-with-operator type (acbc090)
  • remove filter-value-config format (a7172b0)

Features

  • add filter validate option (882a5dc)

0.2.9 (2022-10-21)

Bug Fixes

  • example in README.md & bump version (521fed8)

0.2.8 (2022-10-21)

Bug Fixes

  • typing for parse-query & parse-query-parameter (1924ea7)

0.2.7 (2022-10-21)

Bug Fixes

  • add generic argument for parse-query function (ac0e89f)

0.2.6 (2022-10-20)

Bug Fixes

  • applying default fields with alias (177f5cd)
  • length comparision for key with alias (0ebf707)

0.2.5 (2022-10-20)

Bug Fixes

  • add missing generic type argument for parameters (01f1065)

0.2.4 (2022-10-19)

Bug Fixes

  • add Date type as allowed simple key (44fa46e)

0.2.3 (2022-10-19)

Bug Fixes

  • updated smob dependency (2f0ca15)

0.2.2 (2022-10-19)

Bug Fixes

  • allow global default-path for parse-query method (2580bb9)

0.2.1 (2022-10-18)

Bug Fixes

  • parse query relations typing and allowed matching (b60f9f4)

0.2.0 (2022-10-18)

Features

  • backported defaultAlias as defaultPath (82f820c)

0.1.1 (2022-10-18)

Bug Fixes

  • filter array value transformation + removed unnecessary methods (a02767a)
  • query parameter building + enhanced generation (40d56c4)

0.1.0 (2022-10-15)

Bug Fixes

  • transform filter output value + enhanced typing for filter(s) (cb4cafb)

Features

  • add default & default-by-element option for filter(s) parsing (c2e552d)
  • allow specifying default sort column(s) for parsing (0029731)

0.0.6 (2022-10-10)

Bug Fixes

  • specify depedanbot commit message + bump version (9c70aaf)

0.0.5 (2022-10-10)

Bug Fixes

  • sort build input type + updated package.json (5177fb9)