@gutil/config 1.0.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,247 @@
1
+ // src/client.ts
2
+ import { setTimeout as sleep } from "timers/promises";
3
+
4
+ // src/errors.ts
5
+ var ConfigError = class extends Error {
6
+ status;
7
+ constructor(message, options = {}) {
8
+ super(message, { cause: options.cause });
9
+ this.name = "ConfigError";
10
+ this.status = options.status;
11
+ }
12
+ };
13
+
14
+ // src/client.ts
15
+ function parseBaseUrl(raw) {
16
+ let url;
17
+ try {
18
+ url = new URL(raw);
19
+ } catch (error) {
20
+ throw new ConfigError("Invalid `baseUrl`", { cause: error });
21
+ }
22
+ const auth = url.username ? {
23
+ username: decodeURIComponent(url.username),
24
+ password: decodeURIComponent(url.password)
25
+ } : void 0;
26
+ url.username = "";
27
+ url.password = "";
28
+ return { baseUrl: url.toString().replace(/\/+$/, ""), auth };
29
+ }
30
+ function buildUrl(baseUrl, applications, profiles, label) {
31
+ const segments = [
32
+ applications.map(encodeURIComponent).join(","),
33
+ profiles.map(encodeURIComponent).join(",")
34
+ ];
35
+ if (label) segments.push(encodeURIComponent(label.replace(/\//g, "(_)")));
36
+ return `${baseUrl.replace(/\/+$/, "")}/${segments.join("/")}`;
37
+ }
38
+ function buildHeaders(options) {
39
+ const headers = {
40
+ Accept: "application/json",
41
+ ...options.headers
42
+ };
43
+ const { auth } = options;
44
+ if (auth?.username) {
45
+ const token = Buffer.from(
46
+ `${auth.username}:${auth.password ?? ""}`
47
+ ).toString("base64");
48
+ headers.Authorization = `Basic ${token}`;
49
+ }
50
+ return headers;
51
+ }
52
+ function isTimeout(error) {
53
+ return error?.name === "TimeoutError";
54
+ }
55
+ async function requestOnce(url, options) {
56
+ const timeoutMessage = `Request to ${url} timed out after ${options.timeout}ms`;
57
+ let response;
58
+ try {
59
+ response = await options.fetch(url, {
60
+ method: "GET",
61
+ headers: buildHeaders(options),
62
+ signal: AbortSignal.timeout(options.timeout)
63
+ });
64
+ } catch (error) {
65
+ const message = isTimeout(error) ? timeoutMessage : `Request to ${url} failed: ${error?.message ?? String(error)}`;
66
+ throw new ConfigError(message, { cause: error });
67
+ }
68
+ if (!response.ok) {
69
+ await response.body?.cancel().catch(() => void 0);
70
+ throw new ConfigError(
71
+ `Request to ${url} failed with status ${response.status}`,
72
+ {
73
+ status: response.status
74
+ }
75
+ );
76
+ }
77
+ let body;
78
+ try {
79
+ body = await response.json();
80
+ } catch (error) {
81
+ const message = isTimeout(error) ? timeoutMessage : `Invalid JSON response from ${url}`;
82
+ throw new ConfigError(message, { cause: error });
83
+ }
84
+ if (!body || typeof body !== "object" || body.propertySources !== void 0 && !Array.isArray(body.propertySources)) {
85
+ throw new ConfigError(`Unexpected response from ${url}`);
86
+ }
87
+ return body;
88
+ }
89
+ function isRetryable(error) {
90
+ const status = error instanceof ConfigError ? error.status : void 0;
91
+ return status === void 0 || status >= 500;
92
+ }
93
+ async function fetchEnvironment(options) {
94
+ const url = buildUrl(
95
+ options.baseUrl,
96
+ options.applications,
97
+ options.profiles,
98
+ options.label
99
+ );
100
+ for (let attempt = 0; ; attempt++) {
101
+ try {
102
+ return await requestOnce(url, options);
103
+ } catch (error) {
104
+ if (attempt >= options.retries || !isRetryable(error)) throw error;
105
+ await sleep(options.retryDelay);
106
+ }
107
+ }
108
+ }
109
+
110
+ // src/coerce.ts
111
+ var NUMBER_PATTERN = /^-?(0|[1-9]\d*)(\.\d+)?$/;
112
+ function coerceValue(value) {
113
+ if (typeof value !== "string") return value;
114
+ if (value === "true") return true;
115
+ if (value === "false") return false;
116
+ if (value === "null") return null;
117
+ if (NUMBER_PATTERN.test(value)) {
118
+ const num = Number(value);
119
+ if (Number.isInteger(num) && !Number.isSafeInteger(num)) return value;
120
+ return num;
121
+ }
122
+ return value;
123
+ }
124
+
125
+ // src/parser.ts
126
+ function escapeRegExp(value) {
127
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
128
+ }
129
+ function matchesApplication(sourceName, application, profiles) {
130
+ const profilePart = profiles.length ? `(?:-(?:${profiles.map(escapeRegExp).join("|")}))?` : "";
131
+ const pattern = new RegExp(
132
+ `(?:^|[/\\\\\\[\\s'":])${escapeRegExp(application)}${profilePart}\\.(?:ya?ml|properties)(?:$|[\\]\\s'"])`
133
+ );
134
+ return pattern.test(sourceName);
135
+ }
136
+ function parseEnvironment(env, applications, profiles, coerce) {
137
+ const result = /* @__PURE__ */ new Map();
138
+ for (const application of applications) {
139
+ const values = /* @__PURE__ */ Object.create(null);
140
+ for (const { name, source } of env.propertySources ?? []) {
141
+ if (!source || !matchesApplication(name, application, profiles))
142
+ continue;
143
+ for (const [key, raw] of Object.entries(source)) {
144
+ if (Object.hasOwn(values, key)) continue;
145
+ values[key] = coerce ? coerce(raw, key) : raw;
146
+ }
147
+ }
148
+ result.set(application, values);
149
+ }
150
+ return result;
151
+ }
152
+
153
+ // src/config.ts
154
+ var Config = class _Config {
155
+ client;
156
+ applications;
157
+ profiles;
158
+ coerce;
159
+ data = null;
160
+ pending = null;
161
+ /** 创建实例并完成首次加载 */
162
+ static async create(options) {
163
+ const config = new _Config(options);
164
+ await config.load();
165
+ return config;
166
+ }
167
+ constructor(options) {
168
+ const applications = [options.application].flat().filter(Boolean);
169
+ if (!options.baseUrl) throw new ConfigError("`baseUrl` is required");
170
+ if (!applications.length)
171
+ throw new ConfigError("`application` is required");
172
+ const fetchFn = options.fetch ?? globalThis.fetch;
173
+ if (typeof fetchFn !== "function") {
174
+ throw new ConfigError(
175
+ "Global fetch is not available, please pass `fetch` option"
176
+ );
177
+ }
178
+ const profiles = (options.profile ?? "").split(",").map((p) => p.trim()).filter(Boolean);
179
+ if (!profiles.length) profiles.push("default");
180
+ const { baseUrl, auth: urlAuth } = parseBaseUrl(options.baseUrl);
181
+ this.applications = applications;
182
+ this.profiles = profiles;
183
+ this.coerce = options.coerce === false ? void 0 : typeof options.coerce === "function" ? options.coerce : coerceValue;
184
+ this.client = {
185
+ baseUrl,
186
+ applications,
187
+ profiles,
188
+ label: options.label,
189
+ auth: options.auth ?? urlAuth,
190
+ headers: options.headers,
191
+ timeout: options.timeout ?? 1e4,
192
+ retries: options.retries ?? 0,
193
+ retryDelay: options.retryDelay ?? 1e3,
194
+ fetch: fetchFn
195
+ };
196
+ }
197
+ get loaded() {
198
+ return this.data !== null;
199
+ }
200
+ /** 加载配置,已加载时不会重复请求 */
201
+ load() {
202
+ if (this.data) return Promise.resolve();
203
+ return this.refresh();
204
+ }
205
+ /** 重新拉取配置;失败时保留之前的配置 */
206
+ reload() {
207
+ return this.refresh();
208
+ }
209
+ get(key, options = {}) {
210
+ const values = this.values(options.application);
211
+ const fullKey = options.prefix ? `${options.prefix}.${key}` : key;
212
+ return Object.hasOwn(values, fullKey) ? values[fullKey] : options.defaultValue;
213
+ }
214
+ has(key, application) {
215
+ return Object.hasOwn(this.values(application), key);
216
+ }
217
+ /** 获取某个应用的全部配置 */
218
+ all(application) {
219
+ return { ...this.values(application) };
220
+ }
221
+ values(application = this.applications[0]) {
222
+ if (!this.data)
223
+ throw new ConfigError("Config is not loaded, call `load()` first");
224
+ const values = this.data.get(application);
225
+ if (!values)
226
+ throw new ConfigError(`Unknown application "${application}"`);
227
+ return values;
228
+ }
229
+ refresh() {
230
+ this.pending ??= fetchEnvironment(this.client).then((env) => {
231
+ this.data = parseEnvironment(
232
+ env,
233
+ this.applications,
234
+ this.profiles,
235
+ this.coerce
236
+ );
237
+ }).finally(() => {
238
+ this.pending = null;
239
+ });
240
+ return this.pending;
241
+ }
242
+ };
243
+ export {
244
+ Config,
245
+ ConfigError,
246
+ coerceValue
247
+ };
package/package.json CHANGED
@@ -1,54 +1,53 @@
1
1
  {
2
- "name": "@gutil/config",
3
- "version": "1.0.1",
4
- "description": "获取配置中心配置",
5
- "main": "index.js",
6
- "scripts": {
7
- "compile": "rm -rf build && tsc -p tsconfig.json",
8
- "npmpublish": "./tasks/publish.sh",
9
- "test": "jest --detectOpenHandles"
10
- },
11
- "author": "Gengee",
12
- "license": "ISC",
13
- "devDependencies": {
14
- "@types/jest": "^24.0.25",
15
- "@types/node": "^13.1.4",
16
- "husky": "^3.1.0",
17
- "jest": "^24.9.0",
18
- "lint-staged": "^9.5.0",
19
- "prettier": "^1.19.1",
20
- "ts-jest": "^24.2.0",
21
- "typescript": "^3.7.4"
22
- },
23
- "dependencies": {
24
- "rxjs": "^6.5.4"
25
- },
26
- "husky": {
27
- "hooks": {
28
- "pre-commit": "lint-staged"
29
- }
30
- },
31
- "lint-staged": {
32
- "*.{js,md,css,html}": [
33
- "prettier --write",
34
- "git add"
35
- ]
36
- },
37
- "jest": {
38
- "moduleFileExtensions": [
39
- "js",
40
- "json",
41
- "ts"
42
- ],
43
- "roots": [
44
- "src",
45
- "shared"
46
- ],
47
- "testRegex": ".spec.ts$",
48
- "transform": {
49
- "^.+\\.(t|j)s$": "ts-jest"
50
- },
51
- "coverageDirectory": "../coverage",
52
- "testEnvironment": "node"
53
- }
2
+ "name": "@gutil/config",
3
+ "version": "2.0.0",
4
+ "description": "获取配置中心(Spring Cloud Config)配置",
5
+ "license": "ISC",
6
+ "author": "Gengee",
7
+ "type": "commonjs",
8
+ "main": "./dist/index.js",
9
+ "module": "./dist/index.mjs",
10
+ "types": "./dist/index.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "import": {
14
+ "types": "./dist/index.d.mts",
15
+ "default": "./dist/index.mjs"
16
+ },
17
+ "require": {
18
+ "types": "./dist/index.d.ts",
19
+ "default": "./dist/index.js"
20
+ }
21
+ }
22
+ },
23
+ "files": [
24
+ "dist"
25
+ ],
26
+ "engines": {
27
+ "node": ">=18"
28
+ },
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "scripts": {
33
+ "build": "tsup src/index.ts --format cjs,esm --dts --clean",
34
+ "typecheck": "tsc --noEmit",
35
+ "test": "vitest run",
36
+ "test:watch": "vitest",
37
+ "format": "prettier --write .",
38
+ "prepublishOnly": "npm run typecheck && npm test && npm run build",
39
+ "prepare": "husky"
40
+ },
41
+ "devDependencies": {
42
+ "@types/node": "^18.19.0",
43
+ "husky": "^9.1.0",
44
+ "lint-staged": "^15.2.0",
45
+ "prettier": "^3.3.0",
46
+ "tsup": "^8.3.0",
47
+ "typescript": "^5.6.0",
48
+ "vitest": "^2.1.0"
49
+ },
50
+ "lint-staged": {
51
+ "*.{ts,js,mjs,json,md,yaml}": "prettier --write"
52
+ }
54
53
  }
package/index.d.ts DELETED
@@ -1,2 +0,0 @@
1
- export { Config } from "./src/config";
2
- export { ConfigOptions } from "./src/interface/config.interface";
package/index.js DELETED
@@ -1,5 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- var config_1 = require("./src/config");
4
- exports.Config = config_1.Config;
5
- //# sourceMappingURL=index.js.map
package/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":";;AAAA,uCAAsC;AAA7B,0BAAA,MAAM,CAAA"}
@@ -1,8 +0,0 @@
1
- import { Observable } from "rxjs";
2
- import { RequestOptions } from "../interface/request-option.interface";
3
- export declare abstract class Adaptor {
4
- validateStatus(status: number): boolean;
5
- abstract request(url: string, options?: RequestOptions): Observable<{
6
- [key: string]: any;
7
- }>;
8
- }
@@ -1,9 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- class Adaptor {
4
- validateStatus(status) {
5
- return status >= 200 && status < 300;
6
- }
7
- }
8
- exports.Adaptor = Adaptor;
9
- //# sourceMappingURL=adaptor.abstract.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"adaptor.abstract.js","sourceRoot":"","sources":["../../../src/adaptor/adaptor.abstract.ts"],"names":[],"mappings":";;AAEA,MAAsB,OAAO;IACzB,cAAc,CAAC,MAAc;QACzB,OAAO,MAAM,IAAI,GAAG,IAAI,MAAM,GAAG,GAAG,CAAC;IACzC,CAAC;CAKJ;AARD,0BAQC"}
@@ -1,6 +0,0 @@
1
- import { Adaptor } from "./adaptor.abstract";
2
- import { RequestOptions } from "../interface/request-option.interface";
3
- export declare class NodeAdaptor extends Adaptor {
4
- private getAuth;
5
- request(url: string, options?: RequestOptions): any;
6
- }
@@ -1,60 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const http = require("http");
4
- const https = require("https");
5
- const nodeUrl = require("url");
6
- const rxjs_1 = require("rxjs");
7
- const config_exception_1 = require("../config.exception");
8
- const adaptor_abstract_1 = require("./adaptor.abstract");
9
- class NodeAdaptor extends adaptor_abstract_1.Adaptor {
10
- getAuth(auth) {
11
- if (!auth || !auth.userName || !auth.password)
12
- return null;
13
- return `${auth.userName}:${auth.password}`;
14
- }
15
- request(url, options) {
16
- return rxjs_1.Observable.create((observer) => {
17
- const URL = nodeUrl.parse(url);
18
- const isSSL = URL.protocol === "https:";
19
- const client = (isSSL ? https : http).request({
20
- protocol: URL.protocol,
21
- hostname: URL.hostname,
22
- port: URL.port,
23
- path: URL.pathname,
24
- method: options.method || "GET",
25
- auth: this.getAuth(options.auth),
26
- headers: Object.assign({ "Content-Type": "application/json" }, options.headers || {}),
27
- timeout: options.timeout || 0,
28
- rejectUnauthorized: true
29
- }, (response) => {
30
- const result = [];
31
- const { statusCode } = response;
32
- if (!this.validateStatus(statusCode)) {
33
- observer.error(new config_exception_1.ConfigException(`Request Fail! Status Code: ${statusCode}`));
34
- }
35
- response.on("data", (data) => {
36
- result.push(data);
37
- });
38
- response.on("end", () => {
39
- try {
40
- const body = JSON.parse(result.toString());
41
- observer.next(body);
42
- observer.complete();
43
- }
44
- catch (error) {
45
- observer.error(new config_exception_1.ConfigException(error));
46
- }
47
- });
48
- response.on("error", (error) => {
49
- observer.error(new config_exception_1.ConfigException(error));
50
- });
51
- });
52
- client.on("error", (error) => {
53
- observer.error(new config_exception_1.ConfigException(error));
54
- });
55
- client.end();
56
- });
57
- }
58
- }
59
- exports.NodeAdaptor = NodeAdaptor;
60
- //# sourceMappingURL=node.adaptor.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"node.adaptor.js","sourceRoot":"","sources":["../../../src/adaptor/node.adaptor.ts"],"names":[],"mappings":";;AAAA,6BAA6B;AAC7B,+BAA+B;AAC/B,+BAA+B;AAC/B,+BAAkC;AAClC,0DAAsD;AACtD,yDAA6C;AAG7C,MAAa,WAAY,SAAQ,0BAAO;IAE5B,OAAO,CACX,IAAsB;QAEtB,IAAG,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,QAAQ,IAAI,CAAC,IAAI,CAAC,QAAQ;YAAE,OAAO,IAAI,CAAC;QAC1D,OAAO,GAAG,IAAI,CAAC,QAAQ,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;IAC/C,CAAC;IAED,OAAO,CACH,GAAU,EACV,OAAwB;QAExB,OAAO,iBAAU,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAC,EAAE;YACjC,MAAM,GAAG,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;YAC/B,MAAM,KAAK,GAAG,GAAG,CAAC,QAAQ,KAAK,QAAQ,CAAC;YACxC,MAAM,MAAM,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC;gBAC1C,QAAQ,EAAE,GAAG,CAAC,QAAQ;gBACtB,QAAQ,EAAE,GAAG,CAAC,QAAQ;gBACtB,IAAI,EAAE,GAAG,CAAC,IAAI;gBACd,IAAI,EAAE,GAAG,CAAC,QAAQ;gBAClB,MAAM,EAAE,OAAO,CAAC,MAAM,IAAI,KAAK;gBAC/B,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC;gBAChC,OAAO,EAAE,MAAM,CAAC,MAAM,CAClB,EAAC,cAAc,EAAE,kBAAkB,EAAC,EAAC,OAAO,CAAC,OAAO,IAAI,EAAE,C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C,CAAC,CAAC,CAAC;YACH,MAAM,CAAC,GAAG,EAAE,CAAC;QACjB,CAAC,CAAC,CAAC;IACP,CAAC;CACJ;AAxDD,kCAwDC"}
package/src/config.d.ts DELETED
@@ -1,15 +0,0 @@
1
- import { ConfigOptions, ConfigGetOptions } from "./interface/config.interface";
2
- export declare class Config {
3
- private config;
4
- private options;
5
- constructor(options: ConfigOptions);
6
- private getRequestUrl;
7
- private getAdator;
8
- private getApplicationFlag;
9
- private getFlagKey;
10
- private formateValues;
11
- private fetch;
12
- load(): Promise<void>;
13
- reload(): Promise<void>;
14
- get(key: string, options?: ConfigGetOptions): any;
15
- }
@@ -1,3 +0,0 @@
1
- export declare class ConfigException extends Error {
2
- constructor(message: any);
3
- }
@@ -1,9 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- class ConfigException extends Error {
4
- constructor(message) {
5
- super(message);
6
- }
7
- }
8
- exports.ConfigException = ConfigException;
9
- //# sourceMappingURL=config.exception.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"config.exception.js","sourceRoot":"","sources":["../../src/config.exception.ts"],"names":[],"mappings":";;AAAA,MAAa,eAAgB,SAAQ,KAAK;IACtC,YAAY,OAAW;QACnB,KAAK,CAAC,OAAO,CAAC,CAAC;IACnB,CAAC;CACJ;AAJD,0CAIC"}
package/src/config.js DELETED
@@ -1,113 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- const operators_1 = require("rxjs/operators");
13
- const node_adaptor_1 = require("./adaptor/node.adaptor");
14
- const config_exception_1 = require("./config.exception");
15
- class Config {
16
- constructor(options) {
17
- this.config = null;
18
- let { applicationNames } = options;
19
- if (!Array.isArray(applicationNames))
20
- applicationNames = [applicationNames];
21
- this.options = Object.assign(Object.assign({}, options), { applicationNames });
22
- }
23
- getRequestUrl() {
24
- let { baseUrl, applicationNames, profile = "default", branch } = this.options;
25
- baseUrl = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
26
- applicationNames = Array.isArray(applicationNames) ? applicationNames.join(",") : applicationNames;
27
- let url = `${baseUrl}${applicationNames}/${profile}`;
28
- if (branch)
29
- url += `/${branch}`;
30
- return url;
31
- }
32
- getAdator() {
33
- return new node_adaptor_1.NodeAdaptor();
34
- }
35
- getApplicationFlag(sourceName, applicationNames, profile = "default") {
36
- for (let application of applicationNames) {
37
- const regExp = new RegExp(`${application}(\-${profile})?\.(yaml|properties)`);
38
- if (regExp.test(sourceName))
39
- return application;
40
- }
41
- return null;
42
- }
43
- getFlagKey(key, flag, prefix) {
44
- return [flag, prefix, key].reduce((pre, cur) => {
45
- if (typeof cur !== "undefined")
46
- pre.push(cur);
47
- return pre;
48
- }, []).join(".");
49
- }
50
- formateValues(value) {
51
- if (typeof value === "string") {
52
- if (/^\d+$/.test(value))
53
- return Number(value);
54
- if (value === "true")
55
- return true;
56
- if (value === "false")
57
- return false;
58
- if (value === "null")
59
- return null;
60
- }
61
- return value;
62
- }
63
- fetch() {
64
- const options = this.options;
65
- const adaptor = this.getAdator();
66
- const requestUrl = this.getRequestUrl();
67
- return adaptor
68
- .request(requestUrl, { auth: options.auth })
69
- .pipe(operators_1.map((body) => {
70
- const config = {};
71
- const { applicationNames, profile } = options;
72
- const { propertySources = [] } = body;
73
- for (let property of propertySources) {
74
- const { name, source } = property;
75
- const flag = this.getApplicationFlag(name, applicationNames, profile);
76
- if (!flag || !source)
77
- continue;
78
- for (let key in source) {
79
- const value = this.formateValues(source[key]);
80
- const newKey = this.getFlagKey(key, flag);
81
- config[newKey] = value;
82
- }
83
- }
84
- return config;
85
- }))
86
- .toPromise();
87
- }
88
- load() {
89
- return __awaiter(this, void 0, void 0, function* () {
90
- if (this.config)
91
- return;
92
- this.config = yield this.fetch();
93
- });
94
- }
95
- reload() {
96
- return __awaiter(this, void 0, void 0, function* () {
97
- this.config = null;
98
- return this.load();
99
- });
100
- }
101
- get(key, options = {}) {
102
- if (!this.config)
103
- throw new config_exception_1.ConfigException("The Config is empty! Please load it Before!");
104
- let applicationName = options.applicationName;
105
- let keyPrefix = options.keyPrefix;
106
- if (!applicationName)
107
- applicationName = this.options.applicationNames[0];
108
- const newKey = this.getFlagKey(key, applicationName, keyPrefix);
109
- return this.config[newKey];
110
- }
111
- }
112
- exports.Config = Config;
113
- //# sourceMappingURL=config.js.map
package/src/config.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,8CAAqC;AAErC,yDAAqD;AAErD,yDAAqD;AAErD,MAAa,MAAM;IAGf,YACG,OAAsB;QAHjB,WAAM,GAA2B,IAAI,CAAC;QAK1C,IAAI,EAAE,gBAAgB,EAAE,GAAG,OAAO,CAAC;QACnC,IAAG,CAAC,KAAK,CAAC,OAAO,CAAC,gBAAgB,CAAC;YAAE,gBAAgB,GAAG,CAAE,gBAAgB,CAAE,CAAC;QAC7E,IAAI,CAAC,OAAO,mCACL,OAAO,KACV,gBAAgB,GACnB,CAAC;IACN,CAAC;IAIO,aAAa;QACjB,IAAI,EAAE,OAAO,EAAC,gBAAgB,EAAC,OAAO,GAAC,SAAS,EAAC,MAAM,EAAE,GAAG,IAAI,CAAC,OAAO,CAAC;QACzE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,GAAG,CAA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AS,EAAE,CAAC;IACrB,CAAC;IAKK,IAAI;;YACN,IAAG,IAAI,CAAC,MAAM;gBAAE,OAAO;YACvB,IAAI,CAAC,MAAM,GAAG,MAAM,IAAI,CAAC,KAAK,EAAE,CAAC;QACrC,CAAC;KAAA;IAIK,MAAM;;YACR,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;YACnB,OAAO,IAAI,CAAC,IAAI,EAAE,CAAC;QACvB,CAAC;KAAA;IAID,GAAG,CACC,GAAU,EACV,UAA0B,EAAE;QAE5B,IAAG,CAAC,IAAI,CAAC,MAAM;YAAE,MAAM,IAAI,kCAAe,CAAC,6CAA6C,CAAC,CAAC;QAC1F,IAAI,eAAe,GAAG,OAAO,CAAC,eAAe,CAAC;QAC9C,IAAI,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;QAClC,IAAG,CAAC,eAAe;YAAE,eAAe,GAAG,IAAI,CAAC,OAAO,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAC;QACxE,MAAM,MAAM,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,EAAC,eAAe,EAAC,SAAS,CAAC,CAAC;QAC9D,OAAO,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IAC/B,CAAC;CACJ;AAnID,wBAmIC"}
@@ -1,15 +0,0 @@
1
- import { BasicCredentials } from "./request-option.interface";
2
- export interface ConfigOptions {
3
- baseUrl: string;
4
- applicationNames: Array<string> | string;
5
- profile: string;
6
- branch?: string;
7
- auth?: BasicCredentials;
8
- }
9
- export interface ConfigGetOptions {
10
- applicationName?: string;
11
- keyPrefix?: string;
12
- }
13
- export declare type ConfigStructure = {
14
- [key: string]: string;
15
- };
@@ -1,3 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- //# sourceMappingURL=config.interface.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"config.interface.js","sourceRoot":"","sources":["../../../src/interface/config.interface.ts"],"names":[],"mappings":""}
@@ -1,13 +0,0 @@
1
- export interface BasicCredentials {
2
- userName: string;
3
- password: string;
4
- }
5
- export interface RequestOptions {
6
- url?: string;
7
- method?: string;
8
- auth?: BasicCredentials;
9
- headers?: {
10
- [key: string]: any;
11
- };
12
- timeout?: number;
13
- }