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

meepojs

v0.4.0

Published

JavaScript API generator

Downloads

194

Readme

API Generator

Overview

Generate APIs for HTTP requesting.

Currently use Fetch API, you may need to polyfill it yourself if needed.


Quick Start

First add meepo package to your dependencies:

npm install meepo --save

Then just import and use meepo in your client JavaScript code.


import {
  apis,
  registerApi,
  registerApiSuccChecker,
  onHttpError,
  onApiError,
  beforeRequest,
  beforeResolveBody
} from 'meepo'

// Register global hooks

// API calling will be treated as succeed if and only-if with the body { error_code: 0 } and HTTP status code 200.
registerApiSuccChecker(
  ({ body, status }) => body && body.error_code === 0 && status === 200
)

// Handle API error, which means the `apiSuccessChecker` returns `false` (although HTTP status might be 200)
onApiError(
  ({ body, status, apiConfig }) => {
    throw new Error('API Error Detected')
  }
)

// Handle HTTP error, for example with status code 500.
onHttpError(
  ({ body, status, apiConfig }) => {
    throw new Error('HTTP Error Detected')
  }
)

// Preprocess body data received from backend
registerDataPreprocessor(
  body => body ? body.data : null
)

// Register APIs
registerApi({
  name: 'getUser',
  url: '/api/v1/users/:uid',
  options: {
    method: 'get',
    headers: {
      'Cache-Control': 'no-store',
      'x-black-cat': 'is-a-pretty-cat'
    }
  }
})

registerApi({
  name: 'addUser',
  url: '/api/v1/users/:uid',
  options: {
    method: 'post',
    headers: {
      'Cache-Control': 'no-store',
      'x-black-cat': 'is-a-pretty-cat'
    }
  },
  needs: {
    isSuccess: 'boolean',
    userId: 'number'
  }
})

registerApi({
  name: 'errorAddUser',
  url: '/api/v1/errors/users/:uid',
  options: {
    method: 'post',
    headers: {
      'Cache-Control': 'no-store',
      'x-black-cat': 'is-a-pretty-cat'
    }
  },
  needs: {
    isSuccess: 'boolean',
    userId: 'number'
  }
})

// Call APIs
apis.getUser({
  query: { userName: 'Jinyang', age: 3 },
  params: { uid: 999 }
})
  .then(data => {
    console.log('getUser', data)
  })

apis.addUser({
  body: {
    userId: 123,
    isSuccess: true
  },
  query: { userName: 'Jinyang', age: 3 },
  params: { uid: 999 }
})
  .then(data => {
    console.log('addUser', data)
  })

// Call API with `runWith` method, customized handlers will be used instead of the global one you registered before.
apis.getUser.runWith({
  apiSuccChecker: () => true
})({
  query: { userName: 'Jinyang', age: 3 },
  params: { uid: 999 }
})
  .then(data => {
    console.log('getUser - runWith', data)
  })

APIs

registerApi({ name, url, options, needs })

Register a new API with given params

  • name {string}

    Define name of the API, which can be accessed via apis[name]

  • url {string}

    Define the target url parttern of the API.

    Since there might be search query or params (like :uid below), this url pattern will not be the final requesting url. See apis above.

    e.g. /api/v1/errors/users/:uid.

  • options {Object}

    Options of the API, default (string) value will be marked with *:

    • cache { *default | no-cache | reload | force-cache | only-if-cached }

    • credentials { include | same-origin | *omit }

    • headers {Object} // Customlized headers, default as {}

    • method { *GET | POST | PUT | DELETE | PATCH }

    • mode { no-cors | cors | *same-origin }

    • redirect { manual | *follow | error }

    • referrer { no-referrer | *client }

    • timeout {number}

      Timeout for fetch request, default as 5000ms

    • dataType { *JSON | URLSearchParams | FormData | Origin }

      Will transform body data and set content-type header according to this field:

      • JSON: Set content-type as value application/json, and use JSON.stringfy(body) to serialize the body object.

      • URLSearchParams: Set content-type as value application/x-www-form-urlencoded, and use new URLSearchParams(body) to transform the body.

      • FormData: Set content-type as value multipart/form-data, and use new window.FormData(body) to transform the body.

      • Origin: Do nothing, just pass the body to fetch API.

  • needs {Object}

    This field is optional

    It's obvious that request with GET method doesn't need this.

    API will check the validation of body data passed in, and pass through the necessary data according to this needs Object.

      registerApi({
        // ...
        name: 'createUser',
        needs: {
          isVip: 'boolean',
          userId: 'number',
          'userName?': 'string'
        }
      })
    
      // Error, since missing field `userId`
      apis.createUser({
        // ...
        body: {
          isVip: true,
          userName: 'Jinyang.Li'
        }
      })
    
      // Error, since typeof `userId` should be number
      apis.createUser({
        // ...
        body: {
          userId: '12345',
          isVip: true
        }
      })
    
      // Succeed, since `userName?` is an optional field
      apis.createUser({
        // ...
        body: {
          userId: 12345,
          isVip: true
        }
      })
    
      // Succeed, optional field `userName` will also be sent to the server. `otherData` will not be sent since it's not defined in `needs`
      apis.createUser({
        // ...
        body: {
          userId: 12345,
          isVip: true,
          userName: 'Jinyang.Li',
          otherData: 67890
        }
      })

apis

Object that will hold all registered APIs.

Each API is a function that will start a HTTP request and return a promise with backend data. All fields are optional.

e.g. apis[apiName]({ body, query, params })

  • body {Object}

    Body will be preprocessed according to options.dataType, checked and filtered by needs given in registerApi (if there has one).

  • query {Object}

    Used to generate the query string of request. Here we use URLSearchParams and you may need to polyfill it yourself.

  • params {Object}

Provide the params needed in url parttern.

onHttpError

Register an error handler for HTTP error. When HTTP error catched, the registered callback will be triggered.

registerApiSuccChecker

Register an function to check whether the response data is expected.

onApiError

Register an error handler for APIs. We consider the situation that HTTP request have a normal status while API doesn't receive the expected data as an API error. Whether the response data is expected or not is checked by apiSuccChecker registered before.

beforeRequest

Register an function to preprocess the request body data before sending.

beforeResolveBody

Register an function to preprocess the response body data.

api[name].runWith

We have introduced several function to register global handlers for APIs. Method runWith allow us to generate a new API with customized handlers.

// All handlers are optional, and if not provided, global/default handler will be used.
const newGetUserApi = api.getUser.runWith({
  // ... other handlers
  dataProcessor,
  httpErrorHandler,
})

// Call API
newGetUserApi({ body, params, query })