meepojs

0.4.0 • Public • Published

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 })

Readme

Keywords

Package Sidebar

Install

npm i meepojs

Weekly Downloads

62

Version

0.4.0

License

MIT

Unpacked Size

15.2 kB

Total Files

3

Last publish

Collaborators

  • lithium
  • youxingzhi
  • bbsun
  • gauzewang