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

oiojs

v1.0.7

Published

Powerful and flexible browser Http client, focusing on browser,inspired by Axios and koa-compose

Downloads

8

Readme

oio

Powerful and flexible browser Http client, focusing on browser,inspired by Axios and koa-compose

中文文档

Features

  • Base Methods and configurations of Axios are compatible, but the node.js request module is removed
  • Middleware make business processing easier, such as transforming data for requests and responses
  • Smaller and more flexible, only 5kb(min + gzip)
  • Typescript and Promise support

Install

use npm:

npm install oiojs

Example

Simple example

import oiojs from 'oiojs';
const oio = new oiojs();
oio.setUrl('/').run().then(response => {
  console.log(response.data);
  console.log(response.status);
  console.log(response.statusText);
  console.log(response.headers);
  console.log(response.request);
});

Post request

import oiojs from 'oiojs';
const oio = new oiojs();
// oio.setCtxData({});
const ctx = oio.newCtx();
ctx.setReq({ url: '/', method: 'post', data: {}, params: {} }).run().then(response => console.log(response));
// or 
// ctx.setUrl(url).setMethod('post').setData(data).setParam(params).run().then(response => console.log(response));

Use XHR alone for simple requests

import xhr from 'oiojs/dist/xhr.umd';
// or typescript entry
// import xhr from 'oiojs/src/adapter/xhr';

xhr.get('/').then(response => console.log(response));
xhr.request({ url: '/' }).then(response => console.log(response));
// more methods: delete、head、options、post、put、patch

Use urlencoded format

import oiojs from 'oiojs';
const oio = new oiojs();
const ctx = oio.newCtx();
const data = new URLSearchParams();
data.append('param1', 'value1');
ctx.setReq({
  url: '/',
  data: data,
  method: 'post',
  headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).run().then(response => console.log(response));

Processing Business with Middleware

import oiojs from 'oiojs';
const oio = new oiojs();
// Add middleware
oio.use(async function intercept(ctx, next) {
  const { request, response } = ctx.getCtxData();
  // handler intercept request, for example:
  if (request && !request.data) throw new Error('No Data');
  await next();
  // handler intercept response, for example:
  if (response && response.status === 500) throw new Error('Server Error');
});
oio.use(async function transform(ctx, next) {
  const { request, response } = ctx.getCtxData();
  // handler request data
  await next();
  // handler response data
});
const ctx = oio.newCtx();
ctx.setUrl('https://easy-mock.com/mock/5d567ba461a1c429de63dbc8/api/oio').setData({}).run().then(response => {
    console.log(response);
  }).catch(error => {
    console.log(error);
});

🔥 🔥 🔥 example

Oio Api

Oio extends from Context, But set ajax request to XHR by default

type Extend = { xhr?: XHRRequest } & AnyPlainObj

export default class OiO extends Context {
  constructor (request?: RequestConfig, data?: CtxData, extend?: Extend) {
    super(request || {}, data || {}, merge({ xhr: XHR }, extend || {}))
  }
}
export default class Context {
  // The XHR is default for ajax request
  static XHR: XHRRequest | null
  
  static Event: Event

  // Define default request data config
  protected static $Request: RequestCOnfig

  // Define default response data structure
  protected static $Response: Response<any>

  // Used to isolate from default request
  static newReq () : Request

  // Used to isolate from default response
  static newRes () : Response<any>

  // Storage context data,This context`s data is for middleware use
  protected $data: CtxData

  // request config data
  protected request: RequestConfig

  // response data
  protected response: Response<any>

  // The extend mainly stores references to third-party libraries
  extend: AnyPlainObj

  // The default is XHR for ajax request, If there is no ajax, the oio runs with an error
  xhr: XHRRequest

  // Storage middleware function
  protected middleware: FnNext<Context>[]
  
  // Ignore middleware name list
  protected ignoreMiddlewareFunctionNames: string[]

  /**
   * @param {Request} Request config
   * @param {CtxData} Context data,This context`s data is for middleware use
   * @param extend The extend mainly stores references to third-party libraries
   */
  constructor (request?: RequestConfigj, data?: CtxData, extend?: { xhr?: XHRRequest } & AnyPlainObj)

  /**
   * Create api error for unify
   * @param {string} message The error message.
   * @param {string} [code] The error code (for example, 'ECONNABORTED').
   * @param {Object} [request] The request.
   * @param {Object} [response] The response.
   * @returns {Error} The created error.
   */
  createApiError (message: string, code: string = '', request: Request, response?: Response<any>) : ApiError
  
  /**
   * Add ignore middleware name
   * @param fnNames
   */
  setIgnoreMiddleware (fnNames: string[]) : Context
  
  /**
   * Assert whether middleware is ignored
   * @param name
   */
  assertIgnoreMiddleware (name: string) : boolean
    
  /**
   * Add a middleware
   * @param {FnNext<Context>}
   */
  use (fn: FnNext<any>)

  /**
   * Run middleware
   * @param {FnNext<Context>}
   * @returns {Promise<Response<any>>}
   */
  run (next?: FnNext<any>) : Promise<Response<any>>

  /**
   * Create a new context object for each ajax request
   * @returns {Context} return context, but add $data、request、response、parent attribute in new context
   */
  newCtx () : Context

  /**
   * Setting the context data in the current context
   * This context`s data is for middleware use
   * @param data
   * @returns {Context}
   */
  setCtxData (data: CtxData) : Context

  /**
   * Get the context`s data in the current context
   * @returns {CtxData}
   */
  getCtxData () : CtxData

  /**
   * Setting the request in current context and deep merged request
   * @param {RequestConfig} request config
   * @returns {Context}
   */
  setReq (request: RequestConfigj) : Context

  /**
   * Getting the request in current context
   * The request deep merged request of the parent objects
   * @returns {Request}
   */
  getReq () : Request

  /**
   * Setting the response in current context
   * @param {Response<any>|AnyPlainObj} response data
   * @returns {Context}
   */
  setRes (response: Response<any> | AnyPlainObj) : Context

  /**
   * Getting the response in current context
   * @returns {Response<any>}
   */
  getRes () : Response<any>

  /**
   * Setting the url in current context`s request url
   * @param {String} request url
   * @returns {Context}
   */
  setUrl (url: string) : Context

  /**
   * Setting the method in current context`s request`s method
   * @param {String} delete、get、head、options、post、put、patch
   * @returns {Context}
   */
  setMethod (method: RequestMethod) : Context

  /**
   * Setting the data in current context`s request data
   * @param {RequestData} plain object, string | Document | ArrayBuffer | ArrayBufferView |
   *        URLSearchParams | FormData | File | Blob | ReadableStream<Uint8Array> | null | undefined
   * @returns {Context}
   */
  setData (data: RequestData) : Context

  /**
   * Setting the params in current context`s request params
   * @param {AnyPlainObj} plain object for params
   * @returns {Context}
   */
  setParams (params: RequestParam) : Context
  /**
   * Setting the headers in current context`s request headers
   * @param {AnyPlainObj} headers object
   * @returns {Context}
   */
  setHeaders (headers: AnyPlainObj) : Context
  

XHR Api

XHR.request(config)

XHR.get(url[, request])

XHR.delete(url[, config])

XHR.head(url[, config])

XHR.options(url[, config])

XHR.post(url[, data[, config]])

XHR.put(url[, data[, config]])

XHR.patch(url[, data[, config]])

Request default config

{
  // `url` is the server URL that will be used for the request
  url: '',
  
  // `method` is the request method to be used when making the request
  method: 'get',
  
  // `headers` are custom headers to be sent
  headers: {
    'Content-Type': '', // default object => json、URLSearchParams => urlencoded
    'Accept': 'application/json, text/plain, */*'
  },
  
  // `params` are the URL parameters to be sent with the request
  // Must be a plain object or a URLSearchParams object
  params: null,
  
  // `paramsSerializer` is an optional function in charge of serializing `params`
  paramsSerializer: null,
  
  // `data` is the data to be sent as the request body
  // Only applicable for request methods 'PUT', 'POST', and 'PATCH'
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams,FormData, File, Blob
  data: null,
  
  // `timeout` specifies the number of milliseconds before the request times out.
  // If the request takes longer than `timeout`, the request will be aborted.
  timeout: 0,
  
  // `withCredentials` indicates whether or not cross-site Access-Control requests
  withCredentials: false,
  
  // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
  // This will set an `Authorization` header, For Example { username: 'user', password: '123456' }.
  auth: null,
  
  // `responseType` indicates the type of data that the server will respond with
  // options are: 'arraybuffer', 'document', 'json', 'text', 'stream', 'blob'
  responseType: 'json',
  
  // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
  xsrfCookieName: 'XSRF-TOKEN',
  
  // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
  xsrfHeaderName: 'X-XSRF-TOKEN',
  
  // `onDownloadProgress` allows handling of progress events for downloads
  onDownloadProgress: null,
  
  // `onUploadProgress` allows handling of progress events for uploads
  onUploadProgress: null
  
  // xhr abort, cancel is abort callback
  cancelToken: null,

Response Schema

interface Response<T> {
  // `data` is the response that was provided by the server
  data: T,

  // `status` is the HTTP status code from the server response
  status: number,

  // `statusText` is the HTTP status message from the server response
  statusText: string,

  // `headers` the headers that the server responded with
  // All header names are lower cased
  headers: AnyPlainObj | null,

  // request data
  request: Request | null
}

Project develop

test

npm run test:unit

build

npm run build

Changelog

1.0.6 (2019.12.20)

  • Add RequestConfig cancelToken field for xhr abort
  • Add Context ignore middleware method
  • Optimize code and fix bugs

1.0.1 (2019.8.21)

  • Initial release

License

MIT