0.4.1 • Published 10 months ago

mswx v0.4.1

Weekly downloads
-
License
MIT
Repository
github
Last release
10 months ago

mswx

English|繁體中文

The package is extension to msw(Mock Service Worker).

Currently, provide the following features:

Install

$ npm i mswx

API_PREFIX

Set API prefix, default is http://localhost:5173, if you want to disable it, can set empty string to it.

rest.config.API_PREFIX = 'http://localhost:5173'

Define

A syntactic sugar to define the endpoint, as the below example equals.

  rest.get('/url', (_, res, ctx) => {
    return res(ctx.status(200))
  })
  // and
  rest.define('get', '/url', (_, res, ctx) => {
    return res(ctx.status(200))
  })
  // or
  rest.define({
    method: 'get',
    path: '/url'
  }, (_, res, ctx) => {
    return res(ctx.status(200))
  })

Middleware

Define middleware.

Basic usage

import { rest } from 'mswx'


const AuthTokenMiddleware = rest.middleware((req, res, ctx, next) => {
  const authorization = req.headers.get('Authorization')
  if (authorization === 'Bearer token') {
    // Must call next(), it will continue execute.
    return next()
  }
  return res(ctx.status(401), ctx.json({ message: 'Unauthorized.' }))
})

// The following is the original usage of msw handler.
const authTokenHandlers = [
  rest.get('/token', (_, res, ctx) => {
    return res(
      ctx.status(200),
      ctx.json({
        data: 'token'
      })
    )
  })
]

export const handlers = [
  ...authTokenHandlers.map(AuthTokenMiddleware),
]

Apply multiple middlewares

You can apply multiple middleware as follows:

handlers.map(MiddlewareA).map(MiddlewareB)

Note: execute order is B then A... so on.

For more examples can refer to the test code on GitHub.

0.4.1

10 months ago

0.4.0

1 year ago

0.3.1

1 year ago

0.3.0

1 year ago

0.2.4

1 year ago

0.2.3

1 year ago

0.2.2

1 year ago

0.2.1

1 year ago

0.2.0

1 year ago

0.1.0

1 year ago