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

express-rest-tools

v1.3.2

Published

[![npm version](https://badge.fury.io/js/express-rest-tools.svg)](https://badge.fury.io/js/express-rest-tools)

Downloads

15

Readme

Express Rest Tools

npm version

Install

npm install express-rest-tools

Configulation

| Config key | Default | Type | Description | | ------------------------ | ------------------------------ | -------------- | ----------------------------------------------------------------------------------------------------- | | port | 4000 | Number | Development server port | | corsOptions | {} | Object | Node.js CORS middleware | | logger | false | Bool, Function | Create log format of each activities | | fetchErrorHandler | false | Bool, Function | Handle api response that should be an error (Function must return boolean) | | fetchMessageErrorHandler | false | Bool, Function | Handle error message from api response | | reasons | Resons Types | Object | Reason code and message | | swaggerDefinition | {} | Object | A document that defines or describes an API see more |

Setup and config app in server.js

import { setConfig, useRouter, startServer } from 'express-rest-tools'
import routes from './routes'

const reasons = {
  6: 'Custom description',
  7: 'Custom description'
}

const fetchErrorHandler = res => {
  if (res.status !== 200) return true
  return false
}

const fetchMessageErrorHandler = res => {
  throw Object({
    type: 6,
    th: 'Message',
    en: 'Message',
    technical: 'Message'
  })
}

const logger = (type, datas) => {
  if (type === 'access') {
    return { type }
  }

  if (type === 'activity') {
    return { type }
  }

  if (type === 'response') {
    return { type }
  }

  if (type === 'error') {
    return { type }
  }
}

setConfig({
  port: 4000,
  corsOptions: {},
  reasons,
  swaggerDefinition: {},
  fetchErrorHandler,
  fetchMessageErrorHandler,
  logger
})

useRouter(routes)

startServer()

Reasons Types

// Default
{
  0: 'Success',
  1: 'Failed to fetch service',
  2: 'API error',
  3: 'Validation rules error',
  4: 'File system error',
  5: 'Application error'
}

// Add
setConfig({
  reasons: {
    6: 'Custom descirption',
    7: 'Custom descirption'
  }
})

Throw error

Use throw to return error message

throw Object({
  type: 5, // Reason code
  th: 'Message',
  en: 'Message',
  technical: 'Message'
})

Resonse json format

{
  "transactionID": "G2PC01RKZJSU42YEH-2019/03/04|15:57:44",
  "serviceResult": {
    "status": "ERROR",
    "code": 1,
    "description": "Failed to fetch service"
  },
  "message": {
    "th": "Message",
    "en": "Message",
    "technical": "Message"
  },
  "data": null
}

Server scripts

Dev server

$ npm run dev

Production server

$ npm run start

Testing

$ npm run test
$ npm run test:watch

Listing

$ npm run lint

Utilities

| Name | Description | | ------------- | ----------------------------------------------------------------------------------- | | asyncHandler | Supported throw error in async function then the error will be handle by middleware | | createFetcher | Fetching API and handle error (try/catch) under hood | | useActivity | Log activity |

Example

Wrap controller function and use res({}) to return data

import { asyncHandler } from 'express-rest-tools/lib/utils'

const posts = asyncHandler((req, res) => {
  const postData = []
  res({
    data: postData
  })
})
res({
  headers: {},
  data: any
})

Use axios options

import { createFetcher } from 'express-rest-tools/lib/utils'

const fetchPosts = createFetcher({
  method: 'get',
  url: 'https://jsonplaceholder.typicode.com/posts'
})

const posts = await fetchPosts()

Fetch soap

import { createFetcher } from 'express-rest-tools/lib/utils'

const fetchSoapAPI = createFetcher({
  method: 'post',
  headers: {
    'Content-Type': 'text/xml;charset=UTF-8'
  },
  url: 'http://api',
  data: `xml`
})

const soap = await fetchSoapAPI()
import { useActivity } from 'express-rest-tools/lib/utils'

useActivity({ name: 'fetchPosts' })

Middlewares

| Name | Description | | -------- | --------------------------- | | cache | Cache response in memory | | validate | Validate request with rules |

import { cache } from 'express-rest-tools/lib/middlewares'

// cache(duration)

router.get('/posts', cache(5000, 'prefix'), controller.posts)

Clear Cache

import { clear, clearAll } from 'express-rest-tools/lib/middlewares/cache'

clear('prefix')

clearAll()
import { validate } from 'express-rest-tools/lib/middlewares'
import Joi from 'joi'

// const rules = {
//   query: {},
//   params: {},
//   body: {}
// }

const rules = {
  query: {
    name: Joi.string().required(),
    age: Joi.number().required()
  }
}

// Use a function to get request data

const rules = {
  query: req => ({
    name: Joi.string().required(),
    age: Joi.number().required()
  })
}

router.get('/posts', validate(rules), controller.posts)

Add Middlewares

import { useMiddleware } from 'express-rest-tools'

useMiddleware(yourMiddleware)

API Documentation

The Swagger UI page is https://server/api-docs

Example to write document with Swagger

/**
 * @swagger
 * /users:
 *   get:
 *     description: Returns users
 *     tags: [Users]
 *     parameters:
 *       - in: query
 *         name: "name"
 *         required: true
 *         type: "string"
 *     responses:
 *       200:
 *         description: Success
 */
router.get('/users', controller)