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

margaret-fetcher

v0.11.1

Published

Request classes for fetch

Downloads

6

Readme

Margaret Fetcher

build status npm version npm downloads

Dead simple request classes for fetch.

Usage

To use it simply create a class that extends JsonRequest (or AbstractRequest) and define requests as methods on it. The AbstractRequest class comes with a method per HTTP verb (this.get, this.post etc.).

import {JsonRequest} from 'margaret-fetcher';

export default class UserRequests extends JsonRequest
{
    query = {
        include: 'articles',
    };

    show(user) {
        return this.get(`users/${user}`);
    }

    update(user, attributes) {
        return this.put(`users/${user}`, attributes);
    }

    uploadImage(image) {
        const body = new FormData();
        body.append('image', image);

        return this.make('images', {
            method: 'PUT',
            body,
        });
    }
}

To then use those methods simply call the class anywhere:

import UserRequests from './UserRequests';

const user = new UserRequests().show(3);

You can also use the CrudRequest class which already comes with methods for CRUD endpoints:

import {CrudRequest} from 'margaret-fetcher';

export default class UserRequests extends CrudRequest
{
    resource = 'users';
    query = {include: 'articles'};
}
const requests = new UserRequests();

requests.show(3);
requests.update(3, {foo: 'bar'});
requests.delete(3);

Advanced usage

Configuring options

You can configure options passed with all requests either as one time thing:

// Merge options with the defaults
UserRequests.withOptions({headers: {Authorization: 'Bearer FOOBAR'}}).show(3)

// Override default options
UserRequests.setOptions({headers: {Authorization: 'Bearer FOOBAR'}}).show(3)

Or through the class itself:

class UserRequests extends CrudRequest {
    constructor() {
        super();

        this.withOptions({
            headers: {
                Authorization: `Bearer ${access_token}`,
            }
        });
    }
}

You can also pass callables as any option, and it will only get resolved before each request. Useful if you need to pass options that need to be always up to date:

UserRequests.withOptions({
    headers: {
        Authorization: () => `Bearer ${AuthManager.getToken()}`,
    }
})

Configuring query parameters

You can configure query parameters with the same ease through these provided methods:

// Override all query parameters
UserRequests.setQueryParameters({foo: 'bar'});

// Append new query parameters
UserRequests
    .withQueryParameter('foo', 'bar')
    .withQueryParameter('baz', 'qux');

UserRequests.withQueryParameters({foo: 'bar', baz: 'qux'});

You can also pass arrays to these methods:

UserRequests.withQueryParameter('foo', ['bar', 'baz']); // ?foo[]=bar&foo[]=baz

Configuring middlewares

The promise returned by fetch will be passed through a list of middlewares. By default it will return an object of the data contained in the response. But you can add your own middlewares to perform specific logic.

import {CrudRequest, parseJson, extractData} from 'margaret-fetcher';

class MyRequest extends CrudRequest {
    constructor() {
        super();

        this.setMiddlewares([
          parseJson, // Parses a JSON response
          ::this.extractAuthorizationHeader,
          extractData, // Returns the data contained in a Response object
        ]);
    }

    extractAuthorizationHeader(response) {
        const authorizationHeader = response.headers.get('Authorization');

        // Store it somewhere.

        return response;
    }
}

You can disable all middlewares for a given request using the withoutMiddlewares method:

const users = new UserRequests()
    .withoutMiddlewares()
    .show(3);

Extra helpers

The package also comes with some helper methods for common options:

UserRequests.withBearerToken('FOOBAR').show(3)

You can use a function as well, like for other options:

UserRequests.withBearerToken(::AuthManager.getToken).show(3)

Subrequests

Request classes can be nested at will to build more complex paths. Imagine you have an UserRequests and an ArticleRequests, and that an user can have articles, you can do this:

// GET /users/1/articles/2
new UserRequests()
    .getSubrequest(new ArticleRequests(), 1)
    .show(2);

You can also predefine subrequests through the subrequests property on a request class:

class UserRequests extends AbstractRequest
{
    subrequests = {
        articles: new ArticlesRequests(),  
    }; 
}

And then retrieve it anytime:

new UserRequests().getSubrequest('articles', 1).update(2, attributes);

Raw fetch requests

Sometimes you just need to bypass everything and do a raw fetch request, you can do that through the fetch method:

class UserRequests extends AbstractRequest
{
    uploadSomething(image) {
        const body = new FormData();
        body.append('image', image);

        return this.fetch('images', {
            method: 'PUT',
            body,
        });
    }
}

Testing

$ npm test
$ npm test:watch