Async Services
TangoBoot provides a configuration-based method for creating data service functions. By using defineServices, it is very easy to declare a set of asynchronous service functions for consumption by the view layer or model layer.
Basic Usage
import { defineServices } from '@music163/tango-boot';
const services = defineServices({
list: {
url: 'https://nei.hz.netease.com/api/apimock-v2/c45109399a1d33d83e32a59984b25b00/api/users',
},
add: {
url: 'https://nei.hz.netease.com/api/apimock-v2/c45109399a1d33d83e32a59984b25b00/api/users',
method: 'post',
},
});
call the service function:
async () => {
// simple usage
await services.list();
// call with params, payload the the data passed to request body(for 'get' method, will be query parameters), config the axios request config
await services.add(payload, config);
};
Request Config
defineServices use axios to send requests, so you can pass in the axios request config as the second parameter of the service function.
import { defineServices } from '@music163/tango-boot';
export default defineServices({
list: {
url: 'https://nei.hz.netease.com/api/apimock-v2/c45109399a1d33d83e32a59984b25b00/api/users',
formatter: (res) => {
const { data, message } = res;
return {
code: 200,
list: data,
total: data.length,
message,
};
},
// you can pass other axios config here
},
});
Following is the common configs:
urlrequest urlmethodrequest method,default isGETGETPOSTPUTDELETE
formatterformat the response datarequestTypeencoding type of request body (content-type), default value isjsonjsonBy default, serialize JavaScript objects to JSON.x-www-form-urlencodedequals toapplication/x-www-form-urlencoded
headersrequest headertimeouttimeout of request
more configs should find in axios documentation。
By default, TangoBoot serializes JavaScript objects to JSON. To send data in application/x-www-form-urlencoded format, you can set the requestType to x-www-form-urlencoded.
application/x-www-form-urlencoded data is encoded as key-value pairs separated by '&', with keys and values separated by '='. Non-alphanumeric characters are percent-encoded, which is why this type does not support binary data (use multipart/form-data instead).
Error Messages
The default presentation method of the message when a configuration request error occurs is to use the message component for message overlay display. It is recommended to configure this in the application's entry file.
import { tangoBootConfig } from '@music163/tango-boot';
import { message } from '@music163/antd';
tangoBootConfig.toast = message;