API Template

API Template Generator

General Usage

This part of the generator is used to generate vue's API files, this part has a few features that we can use:

  • Create initial API file

  • Create default API template

  • Adding API functions

This part of the generator use a sub-generator diamond:add-api

All generator command need to be run at the root of your project direction.

Create initial API file

This generator is used to create an empty API template. This can be used if we just want to create an API file and ready for writing our own API functions.

Use the following command to generate the initial template:

yo diamond:add-api Order

Here the first argument is the name of the API, this generator will automatically create a Order.js at /src/api/

.
├─ src
│ └─ Order.js

Order.js 's content will be as follow:

Order.js
import request from '@/utils/request'

Creating default API template

This generator is used to create a RESTful API template. Which contains the most commonly used GET, POST, PUT, DELETE.

Use the following command to generate default template:

yo diamond:add-api Order:default

Same as the initial generator, it will create the an Order.js file. (if it's already exist, it will add in all the default functions)

The content will be as follow:

Order.js
import request from '@/utils/request'

export function getOrder() {
  return request({
    url: '/path/to/api',
    method: 'get'
  })
}

export function saveOrder(data) {
  return request({
    url: '/path/to/api',
    method: 'post',
    data
  })
}

export function updateOrder() {
  return request({
    url: '/path/to/api',
    method: 'put'
  })
}

export function deleteOrder() {
  return request({
    url: '/path/to/api',
    method: 'delete'
  })
}

Adding API functions

This generator is used to add API function to existing API file. If the API file doesn't exist, then it will also generate the file itself.

To add function to specific API, you need to add the action :add after the API name.

Then we can add in the second argument to the generator. This argument require two parameters.

First is the function name, second is the method type. The argument will look like this getOrders:get.

Use the following command to add API function:

yo diamond:add-api Order:add getOrders:get

The function will be added into your API file at /src/api/Order.js.

Last updated