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

rest-collector

v1.0.10

Published

Node.js and browser http library that allows you to merge data from multiple api endpoints

Downloads

25

Readme

Build Status Coverage Status npm version

rest-collector

Rest-Collector is a Node.js and browser http library that allows you to merge data from multiple api endpoints. By adding multiple mappers (explenation bellow), the library allows you to join data from multiple sources into a single entity.

Installing

$ npm install rest-collector

Interface

import { RestCollectorResult } from "rest-collector";

interface RestCollectorResult<E = any> {
    data: E;
    headers: any;
}

Demo: https://codesandbox.io/embed/holy-frost-n222p

API

Basic APIs

Sending get request

const client: RestCollectorClient = new RestCollectorClient("http://server/api/entity/{id}")
const resultArray: RestCollectorResult = await client.get();

console.log("data", resultArray.data);
console.log("headers", resultArray.headers);

const singleData: RestCollectorResult = await client.get({
    params: { id: 1 }
});

console.log("data", singleData.data);

Sending post request

const client: RestCollectorClient = new RestCollectorClient("http://server/api/entity/{id}")
const result: RestCollectorResult = await client.post({
    data: { name: "entity #1" }
});

Sending put request

const client: RestCollectorClient = new RestCollectorClient("http://server/api/entity/{id}")
const result: RestCollectorResult = await client.put({
    params: { id: 1 },
    data: { name: "entity #2" }
});

Sending delete request

const client: RestCollectorClient = new RestCollectorClient("http://server/api/entity/{id}")
const result: RestCollectorResult = await client.delete({
    params: { id: 1 }
});

Adding Mappers

When using microservices architecture you will need to join data from entities in the application level.

const client: RestCollectorClient = new RestCollectorClient("http://server/api/entity/{id}");
client.addMapper({
    entityAttribute: "userId",
    restAPIAttribute: "id",
    restAPIURL: "http://secondserver/api/users",
    mergeEntities: (entity: any, possibleValue: any) => {
        if(possibleValue) {
            entity.email = possibleValue.email;
            return entity;
        }
    }
});
const result = await client.get();
console.log(result.data)

result:

{
    "name": "entity #1",
    "email": "[email protected]"
}

The mapper will join data from both apis, based on the entityAttribute and restAPIAttribute we defined before. addMapper api:

  • entityAttribute: The attribute of the base api on which the joining of the data will take place.
  • restAPIAttribute: The attribute of the other api on which the joining of the data will take place.
  • restAPIURL: The endpoint of the other api.
  • before?: optional - a function which receives the query(get method) or payload (other http methods) and returns a new query/payload to be sent to the other api. This is usefull when you need to adjust the query/payload that you send to the api.
  • method?: optional - the http method for the second api. Defaults to get.
  • retry?: optional - the retries configuration (applies also for the client) - an object with the following properties:
    • retries: number of retries.
    • onFailedAttempt?: optional - a callback on a failed attempt.
    • other options from node-retry: https://github.com/tim-kos/node-retry#retryoperationoptions

You can add more than one mapper to join data from more than one other api.

Adding More Than One Mapper with before method

const client: RestCollectorClient = new RestCollectorClient("http://server/api/entity/{id}");
client.addMapper({
    entityAttribute: "userId",
    restAPIAttribute: "id",
    restAPIURL: "http://secondserver/api/users",
    mergeEntities: (entity: any, possibleValue: any) => {
        if(possibleValue) {
            entity.email = possibleValue.email;
            return entity;
        }
    }
});
client.addMapper({
    entityAttribute: "userId",
    restAPIAttribute: "id",
    restAPIURL: "http://thirdserver/api/users-courses",
    method: "post",
    before: payload => {
        return {
            otherDataForTheApi: [1, 2, 3],
            users: payload,
        };
    },
    mergeEntities: (entity: any, possibleValue: any) => {
        if(possibleValue) {
            entity.course = possibleValue.course;
            return entity;
        }
    }
});
const result = await client.get();
console.log(result.data)

result:

{
    "name": "entity #1",
    "email": "[email protected]",
    "course": "Mathematics"
}

Decorate Requests

In most scenarios you will want to add more meta data information for a specific request such as: transaction id, authentication header or custom headers.

const requestDecorator: DecorateRequest = {
    decorateRequest: (req: RestCollectorRequest, bag: any): void => {
        req.headers.Authorization = "yoursecret!";
        req.headers.transactionid = bag.transactionid;
    };
}
const client: RestCollectorClient = new RestCollectorClient("http://server/api/entity/{id}", requestDecorator);
const result = await client.get({
    bag: { transactionid = "transactionid" }
});

More Usage Examples - https://github.com/taranisag/rest-collector/blob/master/test/test.ts