UNPKG

apisix-client

Version:
520 lines (511 loc) 17.2 kB
"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __defProps = Object.defineProperties; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropDescs = Object.getOwnPropertyDescriptors; var __getOwnPropNames = Object.getOwnPropertyNames; var __getOwnPropSymbols = Object.getOwnPropertySymbols; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __propIsEnum = Object.prototype.propertyIsEnumerable; var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name); var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]); if (__getOwnPropSymbols) for (var prop of __getOwnPropSymbols(b)) { if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]); } return a; }; var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var __async = (__this, __arguments, generator) => { return new Promise((resolve, reject) => { var fulfilled = (value) => { try { step(generator.next(value)); } catch (e) { reject(e); } }; var rejected = (value) => { try { step(generator.throw(value)); } catch (e) { reject(e); } }; var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); step((generator = generator.apply(__this, __arguments)).next()); }); }; var __forAwait = (obj, it, method) => (it = obj[__knownSymbol("asyncIterator")]) ? it.call(obj) : (obj = obj[__knownSymbol("iterator")](), it = {}, method = (key, fn) => (fn = obj[key]) && (it[key] = (arg) => new Promise((yes, no, done) => (arg = fn.call(obj, arg), done = arg.done, Promise.resolve(arg.value).then((value) => yes({ value, done }), no)))), method("next"), method("return"), it); // src/index.ts var src_exports = {}; __export(src_exports, { default: () => src_default }); module.exports = __toCommonJS(src_exports); // src/client.ts var import_axios3 = __toESM(require("axios")); // src/admin/upstream.ts var import_axios = require("axios"); // src/admin/validation.ts var ValidationService = class { constructor(client) { this.validate = (resource, schema) => __async(this, null, function* () { const res = yield this.client.request("post", `/apisix/admin/schema/validate/${resource}`, schema); return res.data; }); this.client = client; } }; // src/admin/upstream.ts var UpstreamService = class { constructor(client) { /** * Fetches specified Upstream by id. * @param id unique id of upstream * @returns {GetResponse<Upstream>} */ this.get = (id) => __async(this, null, function* () { const res = yield this.client.request("get", `/apisix/admin/upstreams/${id}`); return res.data; }); /** * Fetch a list of all configured Upstreams. * @param id unique id of upstream * @param desc description of upstream * @param name name of upstream * @param page offset * @param page_size limit * @returns {PaginationResponse<GetUpstreamResponse>} */ this.getList = (id, desc, name, page, page_size) => __async(this, null, function* () { const res = yield this.client.request( "get", `/apisix/admin/upstreams`, void 0, { id, desc, name, page, page_size } ); return res.data; }); /** * Creates an Upstream and assigns a random id. * @param config {UpstreamDef} * @returns {CreateResponse<Upstream>} */ this.create = (def, validate = false) => __async(this, null, function* () { if (validate) { yield this.validationService.validate("upstreams", def); } const res = yield this.client.request( "post", "/apisix/admin/upstreams", def ); return res.data; }); /** * Creates an Upstream with the specified id. * @param id unique id of upstream * @param config {UpstreamDef} * @returns {CreateResponse<Upstream>} */ this.upsert = (id, config, validate = false) => __async(this, null, function* () { if (validate) { yield this.validationService.validate("upstreams", config); } const res = yield this.client.request( "put", `/apisix/admin/upstreams/${id}`, config ); return res.data; }); /** * Updates the selected attributes of the specified, existing Upstream. To delete an attribute, set value of attribute set to null. * @param id unique id of upstream * @param config {UpstreamDef} * @returns {CreateResponse<Upstream>} */ this.update = (id, config, validate = false) => __async(this, null, function* () { if (validate) { yield this.validationService.validate("upstreams", config); } const res = yield this.client.request( "patch", `/apisix/admin/upstreams/${id}`, config ); return res.data; }); /** * Updates the attribute specified in the path. The values of other attributes remain unchanged. * @param id unique id of upstream * @param path like node * @param config {UpstreamDef} * @returns {CreateResponse<Upstream>} */ this.updateByPath = (id, path, config, validate = false) => __async(this, null, function* () { if (validate) { yield this.validationService.validate("upstreams", config); } const res = yield this.client.request( "patch", `/apisix/admin/upstreams/${id}/${path}`, config ); return res.data; }); /** * Removes the Upstream with the specified id. * @param id unique id of upstream * @returns {void} */ this.delete = (id) => __async(this, null, function* () { yield this.client.request("delete", `/apisix/admin/upstreams/${id}`); }); /** * Is upstream exists ? * @param id unique id of upstream * @returns {boolean} */ this.isExists = (id) => __async(this, null, function* () { try { yield this.get(id); return true; } catch (error) { if ((0, import_axios.isAxiosError)(error) && error.status === 404) { return false; } throw error; } }); this.client = client; this.validationService = new ValidationService(client); } }; // src/admin/route.ts var import_axios2 = require("axios"); var RouteService = class { constructor(client) { this.isJson = (json) => { try { JSON.parse(json); return true; } catch (error) { return false; } }; /** * Fetches specified Route by id. * @param id * @returns */ this.get = (id) => __async(this, null, function* () { const res = yield this.client.request("get", `/apisix/admin/routes/${id}`); return res.data; }); this.getByPath = (path) => __async(this, null, function* () { const res = yield this.client.request( "get", `/apisix/admin/routes?uri=${path}&label=&page=1&page_size=100&host=&desc=&id=` ); return res.data; }); /** * Fetches a list of all configured Routes. * @param name * @param uri * @param label * @param status * @param host * @param id * @param desc * @param page * @param page_size * @returns */ this.getList = (name, uri, label, status, host, id, desc, page, page_size) => __async(this, null, function* () { const res = yield this.client.request( "get", `/apisix/admin/routes`, void 0, { name, uri, label, status, host, id, desc, page, page_size } ); return res.data; }); this.filter = (upstream_id, name, uri, status, host, id, desc, labels, page = "1", page_size = "10") => __async(this, null, function* () { const bufferValues = (yield this.client.etcd.getAll().prefix("/apisix/routes").exec()).kvs.filter((kv) => { return this.isJson(kv.value.toString("utf8")); }); let routes = bufferValues.map((bufferValue) => { return __spreadProps(__spreadValues({}, bufferValue), { key: bufferValue.key.toString("utf8"), value: JSON.parse(bufferValue.value.toString("utf8")) }); }); try { for (var iter = __forAwait(routes), more, temp, error; more = !(temp = yield iter.next()).done; more = false) { const route = temp.value; const upstream_id2 = route.value.upstream_id; if (upstream_id2) { const upstream = (yield this.client.etcd.get(`/apisix/upstreams/${upstream_id2}`).exec()).kvs[0]; if (upstream) { const value = JSON.parse(upstream.value.toString("utf8")); const nodes = value.nodes; if (nodes) { route.value.upstream = value; } } } } } catch (temp) { error = [temp]; } finally { try { more && (temp = iter.return) && (yield temp.call(iter)); } finally { if (error) throw error[0]; } } if (name) { routes = routes.filter((route) => route.value.name.includes(name)); } if (uri) { routes = routes.filter((route) => route.value.uri.includes(uri)); } if (status) { routes = routes.filter((route) => route.value.status === +status); } if (id) { routes = routes.filter((route) => route.value.id.includes(id)); } if (desc) { routes = routes.filter((route) => route.value.desc.includes(desc)); } if (host) { routes = routes.filter( (route) => route.value.upstream && route.value.upstream.nodes && Object.keys(route.value.upstream.nodes).includes(host) ); } if (labels) { const isSearchObjJson = this.isJson(labels); if (isSearchObjJson) { const searchObj = JSON.parse(labels); const keysSearchObj = Object.keys(searchObj); routes = routes.filter((route) => { const sourceObj = route.value.labels; if (sourceObj) { const keysSourceObj = Object.keys(sourceObj); return keysSearchObj.some((key) => keysSourceObj.includes(key) && searchObj[key] === sourceObj[key]); } }); } } if (upstream_id) { routes = routes.filter((route) => route.value.upstream_id.includes(upstream_id)); } return { list: routes.slice((parseInt(page) - 1) * parseInt(page_size), parseInt(page) * parseInt(page_size)).map((slicedRoute) => slicedRoute.value), total: routes.length }; }); /** * Creates a Route and assigns a random id. * @param config * @returns */ this.create = (config, validate = false) => __async(this, null, function* () { if (validate) { yield this.validationService.validate("routes", config); } const res = yield this.client.request("post", `/apisix/admin/routes`, config); return res.data; }); /** * Creates a Route with the specified id. * @param id * @param ttl * @param config * @returns */ this.upsert = (id, config, ttl, validate = false) => __async(this, null, function* () { if (validate) { yield this.validationService.validate("routes", config); } const res = yield this.client.request( "put", `/apisix/admin/routes/${id}${ttl ? `?ttl=${ttl}` : ""}`, config ); return res.data; }); /** * Updates the selected attributes of the specified, existing Route. To delete an attribute, set value of attribute set to null. * @param id * @param config * @returns */ this.update = (id, config, validate = false) => __async(this, null, function* () { if (validate) { yield this.validationService.validate("routes", config); } const res = yield this.client.request( "patch", `/apisix/admin/routes/${id}`, config ); return res.data; }); /** * Updates the attribute specified in the path. The values of other attributes remain unchanged. * @param id * @param path * @param config * @returns */ this.updateByPath = (id, path, config, validate = false) => __async(this, null, function* () { if (validate) { yield this.validationService.validate("routes", config); } const res = yield this.client.request( "patch", `/apisix/admin/routes/${id}/${path}`, config ); return res.data; }); /** * Removes the Route with the specified id. * @param id */ this.delete = (id) => __async(this, null, function* () { yield this.client.request("delete", `/apisix/admin/routes/${id}`); }); this.isExists = (id) => __async(this, null, function* () { try { yield this.get(id); return true; } catch (error) { if ((0, import_axios2.isAxiosError)(error) && error.response && error.response.status === 404) { return false; } else { throw error; } } }); this.client = client; this.validationService = new ValidationService(client); } }; // src/admin/plugin.ts var PluginService = class { constructor(client) { /** * Fetches a list of all Plugins. * @returns {PluginList} */ this.getList = () => __async(this, null, function* () { const res = yield this.client.request("get", `/apisix/admin/plugins/list`); return res.data; }); /** * Get properties for config a plugin * @param pluginName * @returns {any} */ this.getProperties = (pluginName) => __async(this, null, function* () { const res = yield this.client.request("get", `/apisix/admin/plugins/${pluginName}`); return res.data; }); /** * Reloads the plugin according to the changes made in code * @returns {void} */ this.reload = () => __async(this, null, function* () { const res = yield this.client.request("put", `/apisix/admin/plugins/reload`); return res.data; }); this.isExists = (name) => __async(this, null, function* () { const plugins = yield this.getList(); return plugins.indexOf(name) > -1; }); this.client = client; } }; // src/client.ts var import_qs = require("qs"); var import_etcd3 = require("etcd3"); var ApisixAdminClient = class { constructor(connectionConfig, etcdConnectionConfig) { this.request = (method, url, requestBody, query) => __async(this, null, function* () { const config = { method, url }; if (requestBody) { config.data = requestBody; } if (query) { config.params = query; config.paramsSerializer = (params) => (0, import_qs.stringify)(params); } return yield this.client.request(config); }); this.connectionConfig = connectionConfig; this.etcdConnectionConfig = etcdConnectionConfig; this.client = import_axios3.default.create(this.connectionConfig); this.etcd = new import_etcd3.Etcd3(this.etcdConnectionConfig); this.upstream = new UpstreamService(this); this.route = new RouteService(this); this.plugin = new PluginService(this); this.validation = new ValidationService(this); } }; // src/index.ts var src_default = ApisixAdminClient; //# sourceMappingURL=index.js.map