npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

rapiq

v0.9.0

Published

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

Downloads

251,387

Readme

rapiq 🌈

npm version main codecov Known Vulnerabilities semantic-release: angular

Rapiq (Rest Api Query) 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.