You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

68 lines
2.0 KiB

3 years ago
'use strict';
const request = require('superagent')
class paasRequest {
3 years ago
constructor(root, { query = {} } = {}, option) {
3 years ago
this.root = root;
this.query = query
3 years ago
this.option = option
3 years ago
}
3 years ago
3 years ago
#buildUrl = (url) => {
return `${this.root}/${url}`;
}
3 years ago
3 years ago
#resultHandler = (resolve, reject) => {
return (err, res) => {
if (err) {
reject(err);
} else {
3 years ago
resolve(res[this.option.dataWord]);
3 years ago
}
};
}
3 years ago
3 years ago
get = (url, { query = {}, header = {} } = {}) => {
return new Promise((resolve, reject) => {
request.get(this.#buildUrl(url)).set(header).query(Object.assign(query, this.query)).end(this.#resultHandler(resolve, reject));
})
}
3 years ago
3 years ago
post = (url, { data = {}, query = {}, header = {} } = {}) => {
return new Promise((resolve, reject) => {
request.post(this.#buildUrl(url)).set(header).query(Object.assign(query, this.query)).send(data).end(this.#resultHandler(resolve, reject));
})
}
3 years ago
3 years ago
put = (url, { data = {}, header = {}, query = {}, } = {}) => {
return new Promise((resolve, reject) => {
request.put(this.#buildUrl(url)).set(header).query(Object.assign(query, this.query)).send(data).end(this.#resultHandler(resolve, reject));
})
}
3 years ago
3 years ago
delete = (url, { header = {}, query = {} } = {}) => {
return new Promise((resolve, reject) => {
request.delete(this.#buildUrl(url)).set(header).query(Object.assign(query, this.query)).end(this.#resultHandler(resolve, reject));
})
}
3 years ago
}
function factory (app, opts) {
3 years ago
if (opts.pssaRequest) {
try {
for (let r of opts.pssaRequest) {
if (r.name && r.root) {
3 years ago
app.fs[r.name] = new paasRequest(r.root, { ...(r.params || {}) }, { dataWord: r.dataWord || 'body' })
3 years ago
} else {
throw 'opts.pssaRequest 参数错误!'
3 years ago
}
3 years ago
}
} catch (error) {
console.error(error)
process.exit(-1);
}
}
3 years ago
}
module.exports = factory;