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

vite-plugin-mock-simple

v1.0.3

Published

Vite mock simple plugin

Downloads

518

Readme

vite-plugin-mock-simple

npm NPM License PR's Welcome
GitHub last commit Open Source

Provide local mocks for Vite to consume them in your app when running development-server. This is a heavy modified fork of vite-plugin-mock-server by octoape licensed under the MIT-License. Forked to provide a simple vite-mock library.

A mock server plugin for Vite, developed based on TypeScript. And support using TypeScript and JavaScript to write Mock API. When the Mock API file is modified, it will be hot updated automatically. Zero Dependency

Install

node version: >=12.0.0

vite version: >=2.0.0

# if using npm
npm i vite-plugin-mock-simple -D
# if using yarn
yarn add vite-plugin-mock-simple -D

Usage

Config plugin in vite.config.ts and add an array of mocks

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import mockArray from './mockRoutes'

export default defineConfig({
  plugins: [
    vue(),
    mockSimple(mockArray)
  ]
})

Or just fill the mocks in the config file

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import mockSimple, { MockHandler } from 'vite-plugin-mock-simple'

export default defineConfig({
  plugins: [
    vue(),
    mockSimple([
      {
        pattern: '/api/test1/1',
        handle: (req, res) => {
        res.end('Hello world!' + req.url)
      }
    } as MockHandler
    ])
  ]
})

Or import the MockHandler arrays from multiple files

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import mockSimple from 'vite-plugin-mock-simple'
import routes1 from './mock/es.mock'
import routes2 from './mock/cjs.mock'
import routes3 from './mock/apis/es2.mock'
import routes4 from './mock/apis/cjs2.mock'

export default defineConfig({
  plugins: [
    vue(),
    mockSimple([...routes1, ...routes2, ...routes3(), ...routes4])
  ]
})

Mock file examples

The pattern is an ant-style path pattern string, use @howiefh/ant-path-matcher to match the pattern and request URL.

import { MockHandler } from 'vite-plugin-mock-simple'

export default [
  {
    // use method: 'GET' as default
    pattern: '/config.json',
    // Define a json-response directly, with the response-property 👌
    // in that case you cannot define the handle-property
    jsonBody: { databaseUrl: '//:firebaseio.com.', api: 'fake'}
  },
  {
    pattern: '/api/upload/1',
    // use some comma-delimetered values to generate mocks for each of these
    method: 'POST, GET, DELETE, PUT, Patch', 
    handle: (req, res) => {
      // to set an other status code than 200
      res.statusCode = 203 
      res.end('Hello world!' + req.url)
    }
  },
  {
    // optional: to give the app a more real experience
    // delay the time it takes to get the response in millisecounds.
    // 1000 => 1 secound
    delay: 1000
    pattern: '/api/delayed',
    jsonBody: ['1 sec delayed'],
  },
  {
    // * matches zero or more characters
    pattern: '/api/test1/*',
    handle: (req, res) => {
      res.end('Hello world star!' + req.url)
    }
  },
  {
    pattern: '/api/test1/users/{userId}',
    handle: (req, res) => {
      const data = {
        url: req.url,
        params: req.params,
        query: req.query
      }
      res.setHeader('Content-Type', 'application/json')
      res.end(JSON.stringify(data))
    }
  },
  {
    pattern: '/api/test1/body/json',
    method: 'POST',
    handle: (req, res) => {
      res.setHeader('Content-Type', 'application/json')

      // To use the data in the request body, read it from stream:
      // req is incomingMessage which extends stream.Readable 
      // --> https://nodejs.org/api/stream.html#readablereadsize
      // res.end need to be within the function
      // there is a size limit for the bodyString to get parsed 
      req.on('data', (bodyString: string) => { 
        let body: object = JSON.parse(bodyString)
        res.end(JSON.stringify(body))
      })
    }
  },
] as MockHandler[]

Metrics

The plugin will log all mock-routes and requests. These metrics are visible at //localhost:YOUR-PORT/mock-simple/ when your dev-server is running.

Try an example

This repository includes two example apps with some mock-routes

cd ./example2
npm i
npm run dev

Exported types by Module

  • MockHandler, an array of this objects are requiered by this plugin
export type MockHandler = {
  delay?: number,           // optional: time to delay the response in millisecounds
  pattern: string,          // pattern to match urls
  method?: string,          // default method is GET
  handle: (Request: Request, Response: http.ServerResponse) => void || response: Object
  jsonBody?: Object         // XOR to handle, only one of this properties can be defined per handler. A JS-Object that will be returned in json as response body
}
  • Request
type Request = Connect.IncomingMessage & { 
  body?: any, 
  params?: { [key: string]: string }, 
  query?: { [key: string]: string },
  cookies?: { [key: string]: string },
  session?: any
}

License

MIT