vite-plugin-api-serve
TypeScript icon, indicating that this package has built-in type declarations

0.0.5 • Public • Published

vite-plugin-api-serve

npm

Vite plugin to open a local-server that can be load local .js or .ts file as API

Installation

# npm

npm install --save-dev vite-plugin-api-serve


# yarn

yarn add -D vite-plugin-api-serve


# pnpm

pnpm add -D vite-plugin-api-serve

Usage

Create api.config.ts file

Create a js or ts file named 'api. config' in the root directory of the project, which should be at the same level as the vite.config.ts file.

Note: This api.config.ts supports HMR. When we modify this file and save it, the server will automatically restart to ensure that the latest configuration file can be loaded.

file content like this:

// api.config.ts
import { method, path, remote } from "vite-plugin-api-serve/decorator"

export default class DevApiController {
  // static target = "http://xxx.com"

  /**
   * @path: request path
   * @method: request method
   * getData:processing function
   */
  @path("/get-data")
  @method("GET")
  getData({ query }: any) {
    return {
      code: 200,
      msg: "msg",
      data: query,
    }
  }

  @path("/simple-post")
  @method("POST")
  simplePost({ body }: any) {
    return {
      code: 200,
      msg: "msg",
      data: body,
    }
  }

  @path("/post-json")
  @method("POST")
  postWithJSON({ body }: any) {
    return {
      code: 200,
      msg: "msg",
      data: body,
    }
  }

  @path("/post-text")
  @method("POST")
  postWithFormData({ body }: any) {
    return {
      code: 200,
      msg: "msg",
      data: body,
    }
  }

  /**
   * @path: request path
   * @method: request method
   * @remote: remote server address,argment can be set ''
   * getData:processing function
   *
   * If the 'static target=' attribute is set and the 'remote' parameter is not set, the final
   * request address is `http://xxx.com//users/github`. otherwise, the final request address is
   * `https://api.github.com/users/github`
   */
  @path("/users/github")
  @method("GET")
  @remote("https://api.github.com")
  getRemoteData() {}

  @path("/post")
  @method("POST")
  @remote("https://httpbin.org")
  getRemoteDataWithData() {}

  @path("/get")
  @method("GET")
  @remote("https://httpbin.org")
  getRemoteDataWithHeader() {}
}

In version v0.0.2 and below, it should be written in the following format

export default [
  {
    url: "/get-data",
    method: "GET",
    handle: ({ query }) => {
      return {
        code: 200,
        msg: "msg",
        data: query,
      }
    },
  },
]

Import vite-plugin-api-serve and add Plugins option

// vite.config.js

import apiServe from "vite-plugin-api-serve"

export default {
  // ...

  plugins: [apiServe()],
}

Run project

npm run dev

Assuming that the project runs successfully, we can initiate a network request on the '. vue' page, for example:

async function getData() {
  const res = await fetch("/getProjectList")
  const data = await res.json()
  console.log(data.code)
}

If the 'url' and 'method' of the request can be found in the 'api. config' file, the corresponding 'handle' method will be called to process and return the result

About handle function in api.config.js|ts

The handle function is an important component that is called and executed when a route is matched. The complete signature of this function is as follows:

({ body, query, method, headers }, req, res) => Record<string, any> | Error

Although this method provides two objects - 'req' and 'res', but they can be ignored during development. It is better to directly use the four deconstructed objects of {body, query, method, headers}

The return value of this method can be a regular JavaScript object, which will eventually be processed into JSON and returned to the client. If you want to handle certain exceptions, you can return an Error object

  {
    url: "/getProjectList",
    method: "POST",
    handle: ({ body, query, method, headers }) => {
      console.log(body)
      console.log(query)
      console.log(method)
      console.log(headers)
      return {
        name: "getProjectList",
      }
    },
  },

License

MIT

Readme

Keywords

none

Package Sidebar

Install

npm i vite-plugin-api-serve

Weekly Downloads

1

Version

0.0.5

License

MIT

Unpacked Size

16.1 kB

Total Files

6

Last publish

Collaborators

  • qingqingxuan