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

yfetch

v0.2.5

Published

Yet another fetch. A guide for "How to make fetch more beautiful?".

Downloads

18

Readme

yfetch

Yet another fetch. A guide for "How to make fetch more beautiful?".

npm version Build Status Test Coverage License

fetch is a new API based on Promise, it help you to prevent callback hell.

I like fetch, so here is a set of use cases and example codes to know how to use yfetch or make your fetch coding style better.

Core Features:

  • A set of transform functions to help you to deal with fetch request or response.
  • support JSONP at client side.
  • Accept same options just like fetch with some extensions:
    • opts.base : base url
    • opts.query : will be appended into url automatically
    • opts.url : pass into fetch() as 1st param with processed opts.base and opts.query
    • opts.json : auto json headers in request, then json parse the response.body
    • opts.ignoreJsonError : ignore JSON parse error, and the respose.body will be a string
    • opts.error : rejects when the response http code be included in opts.error array
    • response.body : auto resolved as String or JSON
    • response.parsed : true when opts.json successed
    • response.headers : auto transformed as Object from Header
    • response.fetchArgs : the arguments of the fetch call
  • debug , export DEBUG=... to show debug log:
    • yfetch:start: show url and fetch arguments just before the request starts
    • yfetch:raw : show url, response size, status, headers, raw
    • yfetch:result : show url, response status, body as text or JSON
    • yfetch:error : show url, response status, body as text or JSON, error

Install

npm install yfetch --save

You will need these polyfills for older browsers or other environments:

Usage

import yfetch from 'yfetch';

// Same as fetch('https://some.where/test?page=10&size=5', {})
yfetch({
  url: '/test',
  base: 'https://some.where',
  query: {
    page: 10,
    size: 5
  }
}).then((ret) => console.log(ret));

/*
{
  url: 'https://some.where/test?page=10&size=5',
  headers: { ... },
  status: 200,
  statusText: 'OK',
  ok: true,
  body: '...',                                  // yfetch transformed text or JSON
  size: 1234,
  fetchArgs: [                                  // yfetch exntends attribute,
    'https://some.where/test?page=10&size=5',   // original fetch arguments stores here
    {}
  ]
}
*/

JSONP

You will need fetch-jsonp for JSONP feature. When you set { jsonp: true } in yfetch arguments and global.fetchJsonp() exists, the request will made by jsonp.


import yfetch from 'yfetch';

yfetch({
  url: 'http://another.host.com/jsonp',
  jsonp: true,                          // Required for jsonp
  // Allow fetch-jsonp options https://github.com/camsong/fetch-jsonp
  jsonpCallback: 'custom_callback_param_name',            // Optional
  jsonpCallbackFunction: 'custom_callback_function_name', // Optional
}).then((ret) => console.log(ret.body));

To ensure global.fetchJsonp() ready at client side, you can add these:

import fetchJsonp from 'fetch-jsonp'

if (global.window) {
  global.fetchJsonp = fetchJsonp
}

Why I need yfetch?

Check these daily use cases, you may use yfetch to make things simple, or just do the same task with more code.

Get Response body

fetch(url, opts)
.then((response) => response.body.text())
.then (body => {
    // body, but response dropped
});
yfetch({ url, ...opts })
.then(response => {
    // response.body
});

Get Response as JSON

fetch(url, { headers: { Accept: 'application/json' }, ...opts })
.then((response) => response.body.json())
.then (body => {
    // body as JSON, but response dropped
});
yfetch({ url, json: true, ...opts })
.then(response => {
    // response.body as JSON
});

Debug

// ES6 arrow function to return the promise
myfetch = (url, opts) => fetch(url, opts)
.then((response) => response.body.json())
.then (
body => console.log('success', body, url, opts),
error => console.log('error', error, url, opts)
);

// always use the wrapped version
myfetch(url, opts);
// debug in your code....deprecated
yfetch({ url, ...opts })
.then(
resp => console.log('success', resp.body, resp.fetchArgs),
error => console.log('error', error, error.fetchArgs)
);

// BETTER: export DEBUG=yfetch:* then
// just do yfetch without changing your code
yfetch({url, json: true, ...opts})

Conclusion

You always need a wrapped version of fetch for debugging and response handling, you can just use yfetch, or do it your own. If you do not use yfetch, we still encourage you to use ES6 coding style to make your fetch more beautiful. In simple words, yfetch is:

const yfetch = (opts = {}) => {
    const fetchArgs = transformFetchOptions(opts);
    return fetch(...fetchArgs)
    .then(transformForContext(fetchArgs))
    .then(transformFetchResult)
    .catch(transformFetchError(fetchArgs));
}

You can build your own transformFetchOptions, transformForContext, transformFetchResult and transformFetchError , or just enjoy yfetch and reuse the exported yfetch transform functions. Review yfetch source code , then make your decision.

Transform functions

transformFetchOptions(opts)

Deal with opts.base, opts.url and opts.query.

import { transformFetchOptions } from 'yfetch';

transformFetchOptions({}));     // ['', {}]
transformFetchOptions({ base: 'pre_' }));   // ['pre_', {}]
transformFetchOptions({ url: 'test' }));    // ['test', {}]
transformFetchOptions({ base: 'pre_', url: 'test' }));      // ['pre_test', {}]
transformFetchOptions({ url: 'test', query: { foo: 'bar' } }));      // ['test?foo=bar', {}]

transformFetchOptions({ url: 'ya', json: true }));
// ['ya', {
//   json: true,
//   headers: {
//     Accept: 'application/json',
//     'Content-Type': 'application/json' } }]

transformFetchResult(response)

The response must contains .fetchArgs property. Deal with opts.json and opts.error.

import { transformFetchResult } from 'yfetch';

transformFetchResult({body, fetchArgs: [url, {json: true}}]);       // will JSON.parse(body)
transformFetchResult({code: 404, fetchArgs: [url, {error: [404, 500]}}]);   // will throw