Last active
January 10, 2020 00:31
-
-
Save sajov/bc290b7ed76fa5eb70ae8594af71bb88 to your computer and use it in GitHub Desktop.
Feathers js Service Proxy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { Client } = require("undici"); | |
const qs = require("qs"); | |
exports.ServiceProxy = class ServiceProxy { | |
constructor(options) { | |
if (!options.remote) throw new Error("Options expect `remote`"); | |
try { | |
this.client = new Client(options.remote, { | |
connections: options.connections || 100, | |
pipelining: options.pipelining || 10 | |
}); | |
} catch (error) { | |
throw new Error(error); | |
} | |
} | |
async find(params) { | |
const options = this._options(null, params.query); | |
const result = await this._request(options); | |
return result; | |
} | |
async get(id, params) { | |
const options = this._options(id, params.query); | |
const result = await this._request(options); | |
return result; | |
} | |
async create(data, params) { | |
const options = this._options(null, params.query, data); | |
const result = await this._request(options); | |
return result; | |
} | |
async update(id, data, params) { | |
const options = this._options(id, params.query, data, "UPDATE"); | |
const result = await this._request(options); | |
return result; | |
} | |
async patch(id, data, params) { | |
const options = this._options(id, params.query, data, "PATCH"); | |
const result = await this._request(options); | |
return result; | |
} | |
async remove(id, params) { | |
const options = this._options(id, params.query, null, "DELETE"); | |
const result = await this._request(options); | |
return id; | |
} | |
_options(id, params, data, method) { | |
console.log(this.client); | |
const options = { | |
path: this.client.url.pathname, | |
method: method || "GET" | |
}; | |
if (id) options.path = `${options.path}/${id}`; | |
if (params) { | |
const urlParams = qs.stringify(params); | |
if (urlParams != "") options.path = `${options.path}?${urlParams}`; | |
} | |
if (data) options.body = Buffer.from(JSON.stringify(data)); | |
return options; | |
} | |
_request(options) { | |
const self = this; | |
return new Promise(function(resolve, reject) { | |
self.client.request(options, function(err, data) { | |
if (err) reject(err); | |
try { | |
const { statusCode, headers, body } = data; | |
if (statusCode >= 200 && statusCode < 300) { | |
const bufs = []; | |
body.on("data", buf => { | |
bufs.push(buf); | |
}); | |
body.on("end", () => { | |
return resolve(JSON.parse(Buffer.concat(bufs).toString("utf8"))); | |
}); | |
} else { | |
reject(statusCode); | |
} | |
} catch (error) { | |
reject(error); | |
} | |
}); | |
}); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment