Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

meepojs

Package Overview
Dependencies
Maintainers
1
Versions
27
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

meepojs

JavaScript API generator

  • 0.1.3
  • npm
  • Socket score

Version published
Weekly downloads
48
increased by166.67%
Maintainers
1
Weekly downloads
 
Created
Source

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 meeop package to your dependencies:

npm install meeop --save

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


import {
  apis,
  registerApi,
  registerApiSuccChecker,
  registerHttpErrorHandler,
  registerApiErrorHandler,
  registerBodyWillSend,
  registerbodyWillResolve
} from 'meeop'

// 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)
registerApiErrorHandler(
  ({ body, status, apiConfig }) => {
    throw new Error('API Error Detected')
  }
)

// Handle HTTP error, for example with status code 500.
registerHttpErrorHandler(
  ({ 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.

registerHttpErrorHandler

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.

registerApiErrorHandler

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.

registerBodyWillSend

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

registerbodyWillResolve

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

Keywords

FAQs

Package last updated on 19 Jul 2018

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc