@pgds/api-interface 1.2.5

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.
Files changed (65) hide show
  1. package/README.md +410 -0
  2. package/client/FairtrailClient.d.ts +38 -0
  3. package/client/FairtrailClient.js +219 -0
  4. package/client/FairtrailClient.js.map +1 -0
  5. package/client/HttpClient.d.ts +36 -0
  6. package/client/HttpClient.js +360 -0
  7. package/client/HttpClient.js.map +1 -0
  8. package/client/index.d.ts +3 -0
  9. package/client/index.js +8 -0
  10. package/client/index.js.map +1 -0
  11. package/constants/index.d.ts +8 -0
  12. package/constants/index.js +13 -0
  13. package/constants/index.js.map +1 -0
  14. package/errors/index.d.ts +1 -0
  15. package/errors/index.js +72 -0
  16. package/errors/index.js.map +1 -0
  17. package/index.d.ts +7 -0
  18. package/index.js +23 -0
  19. package/lib/auth/mustbeConfig.d.ts +13 -0
  20. package/lib/auth/mustbeConfig.js +167 -0
  21. package/lib/auth/mustbeConfig.js.map +1 -0
  22. package/lib/constants/constants.d.ts +3 -0
  23. package/lib/constants/constants.js +8 -0
  24. package/lib/constants/constants.js.map +1 -0
  25. package/lib/index.d.ts +255 -0
  26. package/lib/index.js +462 -0
  27. package/lib/index.js.map +1 -0
  28. package/lib/models/Http.d.ts +62 -0
  29. package/lib/models/Http.js +3 -0
  30. package/lib/models/Http.js.map +1 -0
  31. package/lib/models/ReqUser.d.ts +10 -0
  32. package/lib/models/ReqUser.js +3 -0
  33. package/lib/models/ReqUser.js.map +1 -0
  34. package/lib/server/server.d.ts +13 -0
  35. package/lib/server/server.js +154 -0
  36. package/lib/server/server.js.map +1 -0
  37. package/lib/utils/asyncHooks.d.ts +28 -0
  38. package/lib/utils/asyncHooks.js +99 -0
  39. package/lib/utils/asyncHooks.js.map +1 -0
  40. package/lib/utils/jsonSchemaUtils.d.ts +14 -0
  41. package/lib/utils/jsonSchemaUtils.js +187 -0
  42. package/lib/utils/jsonSchemaUtils.js.map +1 -0
  43. package/lib/utils/logger.d.ts +5 -0
  44. package/lib/utils/logger.js +33 -0
  45. package/lib/utils/logger.js.map +1 -0
  46. package/lib/utils/urlUtils.d.ts +1 -0
  47. package/lib/utils/urlUtils.js +14 -0
  48. package/lib/utils/urlUtils.js.map +1 -0
  49. package/package.json +104 -0
  50. package/types/hiot.d.ts +368 -0
  51. package/types/mustbe/config/activities.d.ts +11 -0
  52. package/types/mustbe/config/index.d.ts +77 -0
  53. package/types/mustbe/config/parameter-map.d.ts +8 -0
  54. package/types/mustbe/config/route-helpers.d.ts +17 -0
  55. package/types/mustbe/config/user-identity.d.ts +7 -0
  56. package/types/mustbe/core.d.ts +23 -0
  57. package/types/mustbe/identities/userIdentity.d.ts +10 -0
  58. package/types/mustbe/index.d.ts +6 -0
  59. package/types/mustbe/principals/index.d.ts +10 -0
  60. package/types/mustbe/registry.d.ts +11 -0
  61. package/types/mustbe/routeHelpers/index.d.ts +20 -0
  62. package/types/mustbe/verifier/index.d.ts +10 -0
  63. package/utils/index.d.ts +13 -0
  64. package/utils/index.js +32 -0
  65. package/utils/index.js.map +1 -0
package/README.md ADDED
@@ -0,0 +1,410 @@
1
+ ### hiot-api-interface
2
+
3
+
4
+ Examples:
5
+ - [#Example](#example)
6
+ - [./examples/example.ts](examples/example.ts)
7
+ - [./examples/example.js](examples/example.js)
8
+
9
+ ## Exports
10
+
11
+ Available exports
12
+
13
+ ```typescript
14
+ import { get, post, put, patch, del, internal, JsonResponse, prepareJsonSchemas, Method } from "hiot-api-interface";
15
+ ```
16
+
17
+ ## Endpoints
18
+ <details>
19
+ <summary>The <code>get</code>, <code>post</code>, <code>put</code>, <code>patch</code>, <code>del</code> & <code>internal</code> functions are for registering endpoints. They share the same api</summary>
20
+
21
+
22
+ ```typescript
23
+ export default get({
24
+ /** The path to the endpoint */
25
+ path: string,
26
+
27
+ /** The activity that is required to access this endpoint */
28
+ authorized: string,
29
+
30
+ /** Whether you need to be logged in or not to access the endpoint. Only needed if authorized is not used. */
31
+ authenticated?: boolean;
32
+
33
+ /**
34
+ * The request schema, either a JSON schema or the name of a typescript type
35
+ * (See below. The name must match the name of the file in ./api/schemas).
36
+ **/
37
+ requestSchema: string | object;,
38
+
39
+ /** The request handler function */
40
+ requestHandler: (req: Request<any>, res: Response<any>, next: Next) => Promise<JsonResponse<any> | void>,
41
+
42
+ /** Additional route options */
43
+ opts?: RouteOptions;
44
+
45
+ /** The documentation for the endpoint */
46
+ documentation: {
47
+ /** A short summary of the endpoint */
48
+ summary: string,
49
+
50
+ /** A longer description of the endpoint */
51
+ description: string,
52
+
53
+ /** Optional array of tags */
54
+ tags?: string[];
55
+
56
+ /**
57
+ * Optional description for query params (can also be defined and described in the json schema,
58
+ * since that's how we validate them)
59
+ **/
60
+ query?: Record<string, string>;
61
+
62
+ /**
63
+ * Optional description of url parameters.
64
+ * Usually unnecessary since url params should be self descriptive, e.g. /dashboards/:dashboardId
65
+ **/
66
+ parameters?: Record<string, string>;
67
+
68
+ /** The responses that can be returned by the endpoint */
69
+ responses: [
70
+ {
71
+ /** The http status code of the response */
72
+ status: number,
73
+
74
+ /**
75
+ * An optional response schema, either a JSON schema or the name of a typescript type
76
+ * (See below. The name must match the name of the file in ./api/schemas).
77
+ **/
78
+ schema: string,
79
+
80
+ /** An optional description of the response */
81
+ description?: string,
82
+ },
83
+ ],
84
+ },
85
+ });
86
+ ```
87
+
88
+ </details>
89
+
90
+ ### Example
91
+
92
+ ```typescript
93
+ import { get, JsonResponse } from "hiot-api-interface";
94
+
95
+ export const GET_DASHBOARDS_PATH = "/dashboards";
96
+ export const GET_DASHBOARDS_ACTIVITY = ["dashboards", "getDashboards"];
97
+
98
+ export default get({
99
+ path: GET_DASHBOARDS_PATH,
100
+ authorized: GET_DASHBOARDS_ACTIVITY,
101
+ requestSchema: GET_DASHBOARDS_REQUEST_SCHEMA,
102
+ requestHandler: getDashboardsEndpoint,
103
+ documentation: {
104
+ summary: "Get dashboards",
105
+ description: "Gets all dashboards",
106
+ responses: [
107
+ {
108
+ status: 200,
109
+ schema: GET_DASHBOARDS_RESPONSE_SCHEMA,
110
+ },
111
+ ],
112
+ },
113
+ });
114
+
115
+ async function getDashboardsEndpoint(req: Request<GetDashboardsRequestSchema>): Promise<JsonResponse<DashboardModelViewModel[]>> {
116
+ const { q, page = 0, size = 50, sortBy = "updatedAt", sortOrder = -1 } = req.params;
117
+
118
+ // ...
119
+
120
+ /** Throwing exceptions */
121
+ if(!dashboard) {
122
+ throw new NotFoundError("Dashboard not found");
123
+ }
124
+
125
+ /** Return status/data/headers */
126
+ return {
127
+ status: 200 // optional if 200
128
+ body: dashboard.toViewModel(),
129
+ headers: {
130
+ totalcount: dashboardCount,
131
+ }
132
+ };
133
+ }
134
+
135
+ ```
136
+
137
+ `JsonResponse<T>` is the return type. Setting a request handler to return it will validate that the responses are matching the intended response type. E.g. `Promise<JsonResponse<DashboardModelViewModel[]>>`. However, using `res` and `next` is also possible, they are passed in as second and third arguments to the requestHandler function.
138
+
139
+ </details>
140
+
141
+ ## Request schema
142
+ <details>
143
+ <summary>Request schemas can be either a JSON schema or a typescript type</summary>
144
+ When using typescript types as json schemas:
145
+
146
+ Since types are not an actual entity in javascript, they have to be referenced by name (string). Exporting a constant with the name of the type is the easiest way to do this (see `export const GET_DASHBOARDS_REQUEST_SCHEMA = "GetDashboardsRequestSchema";` below). Not that the name must match the name of the file in `./api/schemas`. Having an export inside the schema file makes it easier to navigate to the schema from the endpoint file (e.g. ctrl/cmd + click. Whereas just using a string mean you would have to search for it manually).
147
+
148
+ The conversion is done by `typescript-json-schema` and supports annotations for things such as max, min etc, read more about how to annotate types [here](https://www.npmjs.com/package/typescript-json-schema#user-content-annotations).
149
+
150
+ They can be exported as:
151
+
152
+ ```typescript
153
+ export const GET_DASHBOARDS_REQUEST_SCHEMA = "GetDashboardsRequestSchema";
154
+
155
+ /** Query params */
156
+ export type GetDashboardsRequestSchema = {
157
+ q?: string;
158
+
159
+ sortBy?: "name" | "createdAt";
160
+
161
+ /**
162
+ * @minimum -1
163
+ * @maximum 1
164
+ */
165
+ sortOrder?: string;
166
+
167
+ /** Number */
168
+ size?: string;
169
+
170
+ /** Number */
171
+ page?: string;
172
+ };
173
+ ```
174
+
175
+ Is translated into, at run time:
176
+
177
+ ```typescript
178
+ export const GetDashboardsRequestSchema = {
179
+ type: "object",
180
+ description: "Query params",
181
+ properties: {
182
+ q: {
183
+ type: "string",
184
+ },
185
+ sortBy: {
186
+ type: "string",
187
+ enum: ["name", "createdAt"],
188
+ },
189
+ sortOrder: {
190
+ type: "string",
191
+ minimum: -1,
192
+ maximum: 1,
193
+ },
194
+ size: {
195
+ type: "string",
196
+ description: "Number",
197
+ },
198
+ page: {
199
+ type: "string",
200
+ description: "Number",
201
+ },
202
+ },
203
+ };
204
+ ```
205
+ </details>
206
+
207
+ ## Response schema
208
+ <details>
209
+ <summary>Response schemas can be either a JSON schema or a typescript type</summary>
210
+
211
+
212
+ ```typescript
213
+ import { DashboardModel } from "../../models/DashboardModel";
214
+
215
+ export const GET_DASHBOARDS_RESPONSE_SCHEMA = "GetDashboardsResponseSchema";
216
+
217
+ export type GetDashboardsResponseSchema = DashboardModel[];
218
+ ```
219
+ </details>
220
+
221
+ ## Json schema setup
222
+
223
+ <details>
224
+ <summary>Using typescript types as json schemas require them to be converted to json schemas during run time. This is done during the service startup. Schemas are cached so that they are only converted once when running tests (that are restarting the service for each test file).</summary>
225
+
226
+
227
+ ```typescript
228
+ import { setupApiInterface } from "hiot-api-interface";
229
+
230
+ const started = hiot
231
+ .startApp({ logger, onUncaughtException: handleException, handleException })
232
+ .then((locator)=>{
233
+ await setupApiInterface({
234
+ port: PORT,
235
+ apiVersion: "v1",
236
+ serviceLogLevel: "info",
237
+ serviceName: "visualisation-svc",
238
+ typescript: true,
239
+ });
240
+
241
+ routes();
242
+
243
+ return locator;
244
+ })
245
+ .then(waitFor)
246
+ .then(db)
247
+ .then(shutdown)
248
+ .then(setDatabaseIndexes)
249
+ .catch(hiot.failed(logger));
250
+ ```
251
+
252
+ </details>
253
+
254
+
255
+ ## routes.ts
256
+
257
+ <details>
258
+ <summary>
259
+ To maintain control over when the endpoints are registered, they still have to be initiated, this is still done in <code>./api/routes.ts</code>, by importing the endpoint files and calling the exported function.
260
+ </summary>
261
+
262
+ ```typescript
263
+ import getDashboardByIdEndpoint from "./dashboard/getDashboardByIdEndpoint";
264
+
265
+ export default function () {
266
+ getDashboardsEndpoint();
267
+ }
268
+ ```
269
+
270
+ This is equal to doing (since all the endpoint details are set in the endpoint file):
271
+
272
+ ```typescript
273
+ import getDashboardByIdEndpoint from "./dashboard/getDashboardByIdEndpoint";
274
+
275
+ export default function (server: restify.Server) {
276
+ /*
277
+ * @api [get] /dashboards
278
+ * tags:
279
+ * - dashboards
280
+ * summary: "Get dashboards"
281
+ * description: "Gets all dashboards"
282
+ * responses:
283
+ * "200":
284
+ * description: "The dashboards found"
285
+ * schema:
286
+ * type: "object"
287
+ * description: "Query params"
288
+ * // ...the rest of the schema as a manual swagger comment
289
+ */
290
+ api.get(
291
+ route(GET_DASHBOARDS_PATH),
292
+ validate(GetDashboardsRequestSchema),
293
+ mustBe.authorized(GET_DASHBOARDS_ACTIVITY),
294
+ getDashboardsEndpoint
295
+ );
296
+ }
297
+ ```
298
+ </details>
299
+
300
+ ## Testing
301
+
302
+ <details>
303
+ <summary>Testing is done like any other test.</summary>
304
+
305
+ ```typescript
306
+
307
+ ### Through sandbox
308
+
309
+ ```typescript
310
+ describe("getDashboardsEndpoint", () => {
311
+ it("should...", async () => {
312
+ const { status, body, headers } = await box.api
313
+ .get(`/v1${GET_DASHBOARDS_PATH}`)
314
+ .set(AUTH_USER_HEADER, user.userId)
315
+ .set(AUTH_ACTIVITIES_HEADER, GET_DASHBOARDS_ACTIVITY);
316
+
317
+ // ...
318
+ });
319
+ });
320
+ ```
321
+
322
+ ### Directly on handler
323
+
324
+ If an endpoint needs to be tested directly, it can be done like this:
325
+
326
+ ```typescript
327
+ import getDashboardByIdEndpoint from "../api/dashboard/getDashboardByIdEndpoint";
328
+
329
+ describe("getDashboardsEndpoint", () => {
330
+ it("should...", async () => {
331
+ const { status, body, headers } = await getDashboardsEndpoint.requestHandler({
332
+ params: {
333
+ q: "test",
334
+ page: "0",
335
+ size: "50",
336
+ sortBy: "updatedAt",
337
+ sortOrder: "-1",
338
+ },
339
+ user: {
340
+ userId: user.userId,
341
+ activities: GET_DASHBOARDS_ACTIVITY,
342
+ },
343
+ });
344
+
345
+ // ...
346
+ });
347
+ });
348
+ ```
349
+
350
+ The export of the endpoint file is both a function for registering the endpoint and an object with the request handler.
351
+
352
+ </details>
353
+
354
+
355
+
356
+ # Publishing
357
+ Prerequisites:
358
+ - You have to be part of the @hiotlabs organization on npm
359
+ - You have to be logged in to npm
360
+
361
+ Then, in root, run:
362
+ ```typescript
363
+ // Check out any untracked/ignored files (e.g. previously built files)
364
+ yarn clean
365
+
366
+ // Install dependencies
367
+ yarn install
368
+
369
+ // Build
370
+ yarn build
371
+
372
+ // Make sure tests pass
373
+ yarn test
374
+
375
+ // Publish
376
+ npm publish --access private
377
+
378
+ // Or pack (for testing)
379
+ npm pack
380
+ ```
381
+
382
+
383
+
384
+ # Adding new directories to the project (@hiotlabs/hiot-api-interface)
385
+ <details>
386
+
387
+ - Create folder
388
+ - Add index.ts file in the folder
389
+ - This file will be responsible for exporting functions.
390
+ - Add one entry for `.js`, `.js.map` and `.d.ts` for the folder to package.json's `files` array, e.g. `utils/**/*.js`, `utils/**/*.js.map` and `utils/**/*.d.ts`
391
+
392
+ ```json
393
+ "files": [
394
+ "**/*.d.ts",
395
+ "./index.js",
396
+ "lib/**/*.js",
397
+ "lib/**/*.js.map",
398
+ "lib/**/*.d.ts",
399
+ "errors/**/*.js",
400
+ "errors/**/*.js.map",
401
+ "errors/**/*.d.ts",
402
+ "constants/**/*.js",
403
+ "constants/**/*.js.map",
404
+ "constants/**/*.d.ts",
405
+ "utils/**/*.js",
406
+ "utils/**/*.js.map",
407
+ "utils/**/*.d.ts"
408
+ ],
409
+ ```
410
+ </details>
@@ -0,0 +1,38 @@
1
+ import { ReqUser } from "../lib/models/ReqUser";
2
+ import { HttpClient } from "./HttpClient";
3
+ /**
4
+ * A backend client for making requests to the Fairtrail API.
5
+ *
6
+ * Provides authentication functions and provides internal methods for making requests to internal endpoints.
7
+ */
8
+ export declare class FairtrailClient extends HttpClient {
9
+ private reqUser;
10
+ private reqAsGlobal;
11
+ private reqAsOrganizationManager;
12
+ private reqOrganizationId;
13
+ protected get internal(): {
14
+ get: (options: Parameters<typeof this.get>[0]) => Promise<import("axios").AxiosResponse<any, any>>;
15
+ post: (options: Parameters<typeof this.post>[0]) => Promise<import("axios").AxiosResponse<any, any>>;
16
+ put: (options: Parameters<typeof this.put>[0]) => Promise<import("axios").AxiosResponse<any, any>>;
17
+ patch: (options: Parameters<typeof this.patch>[0]) => Promise<import("axios").AxiosResponse<any, any>>;
18
+ delete: (options: Parameters<typeof this.delete>[0]) => Promise<import("axios").AxiosResponse<any, any>>;
19
+ };
20
+ private getNewInstance;
21
+ /**
22
+ * Makes any subsequent requests as the provided user.
23
+ * @param user can be a partial user object, only the provided fields will be used, will default to the service user for any missing fields.
24
+ */
25
+ asUser(user?: Partial<ReqUser>): Omit<this, "asOrganizationManager" | "asGlobal" | "asUser">;
26
+ /**
27
+ * Makes any subsequent requests as the global user.
28
+ * @param useAsGlobal typically not used, but can be used with conditional logic to determine if the request should be made as a global user
29
+ */
30
+ asGlobal(useAsGlobal?: boolean): Omit<this, "asOrganizationManager" | "asGlobal" | "asUser">;
31
+ /**
32
+ * Makes any subsequent requests as an organization manager.
33
+ * @param useAsOrganizationManagerOrOrganizationId typically not used, but can be used with conditional logic to determine if the request should be made as an organization manager. Can also be used to specify the organization id to manage.
34
+ */
35
+ asOrganizationManager(useAsOrganizationManagerOrOrganizationId?: boolean | string): Omit<this, "asOrganizationManager" | "asGlobal" | "asUser">;
36
+ private get serviceApiUser();
37
+ protected getAuthHeaders(): Promise<Record<string, string>>;
38
+ }
@@ -0,0 +1,219 @@
1
+ "use strict";
2
+ var __extends = (this && this.__extends) || (function () {
3
+ var extendStatics = function (d, b) {
4
+ extendStatics = Object.setPrototypeOf ||
5
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
+ return extendStatics(d, b);
8
+ };
9
+ return function (d, b) {
10
+ if (typeof b !== "function" && b !== null)
11
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
+ extendStatics(d, b);
13
+ function __() { this.constructor = d; }
14
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
+ };
16
+ })();
17
+ var __assign = (this && this.__assign) || function () {
18
+ __assign = Object.assign || function(t) {
19
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
20
+ s = arguments[i];
21
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
22
+ t[p] = s[p];
23
+ }
24
+ return t;
25
+ };
26
+ return __assign.apply(this, arguments);
27
+ };
28
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
29
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
30
+ return new (P || (P = Promise))(function (resolve, reject) {
31
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
32
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
33
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
34
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
35
+ });
36
+ };
37
+ var __generator = (this && this.__generator) || function (thisArg, body) {
38
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
39
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
40
+ function verb(n) { return function (v) { return step([n, v]); }; }
41
+ function step(op) {
42
+ if (f) throw new TypeError("Generator is already executing.");
43
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
44
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
45
+ if (y = 0, t) op = [op[0] & 2, t.value];
46
+ switch (op[0]) {
47
+ case 0: case 1: t = op; break;
48
+ case 4: _.label++; return { value: op[1], done: false };
49
+ case 5: _.label++; y = op[1]; op = [0]; continue;
50
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
51
+ default:
52
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
53
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
54
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
55
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
56
+ if (t[2]) _.ops.pop();
57
+ _.trys.pop(); continue;
58
+ }
59
+ op = body.call(thisArg, _);
60
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
61
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
62
+ }
63
+ };
64
+ Object.defineProperty(exports, "__esModule", { value: true });
65
+ exports.FairtrailClient = void 0;
66
+ var constants_1 = require("../constants");
67
+ var lib_1 = require("../lib");
68
+ var constants_2 = require("../lib/constants/constants");
69
+ var HttpClient_1 = require("./HttpClient");
70
+ /**
71
+ * A backend client for making requests to the Fairtrail API.
72
+ *
73
+ * Provides authentication functions and provides internal methods for making requests to internal endpoints.
74
+ */
75
+ var FairtrailClient = /** @class */ (function (_super) {
76
+ __extends(FairtrailClient, _super);
77
+ function FairtrailClient() {
78
+ var _this = _super !== null && _super.apply(this, arguments) || this;
79
+ _this.reqAsGlobal = false;
80
+ _this.reqAsOrganizationManager = false;
81
+ return _this;
82
+ }
83
+ Object.defineProperty(FairtrailClient.prototype, "internal", {
84
+ get: function () {
85
+ var _this = this;
86
+ return {
87
+ get: function (options) { return __awaiter(_this, void 0, void 0, function () {
88
+ return __generator(this, function (_a) {
89
+ switch (_a.label) {
90
+ case 0: return [4 /*yield*/, this.get(__assign(__assign({}, options), { path: "".concat(constants_2.INTERNAL_ENDPOINT_PREFIX).concat(options.path) }))];
91
+ case 1: return [2 /*return*/, _a.sent()];
92
+ }
93
+ });
94
+ }); },
95
+ post: function (options) { return __awaiter(_this, void 0, void 0, function () {
96
+ return __generator(this, function (_a) {
97
+ switch (_a.label) {
98
+ case 0: return [4 /*yield*/, this.post(__assign(__assign({}, options), { path: "".concat(constants_2.INTERNAL_ENDPOINT_PREFIX).concat(options.path) }))];
99
+ case 1: return [2 /*return*/, _a.sent()];
100
+ }
101
+ });
102
+ }); },
103
+ put: function (options) { return __awaiter(_this, void 0, void 0, function () {
104
+ return __generator(this, function (_a) {
105
+ switch (_a.label) {
106
+ case 0: return [4 /*yield*/, this.put(__assign(__assign({}, options), { path: "".concat(constants_2.INTERNAL_ENDPOINT_PREFIX).concat(options.path) }))];
107
+ case 1: return [2 /*return*/, _a.sent()];
108
+ }
109
+ });
110
+ }); },
111
+ patch: function (options) { return __awaiter(_this, void 0, void 0, function () {
112
+ return __generator(this, function (_a) {
113
+ switch (_a.label) {
114
+ case 0: return [4 /*yield*/, this.patch(__assign(__assign({}, options), { path: "".concat(constants_2.INTERNAL_ENDPOINT_PREFIX).concat(options.path) }))];
115
+ case 1: return [2 /*return*/, _a.sent()];
116
+ }
117
+ });
118
+ }); },
119
+ delete: function (options) { return __awaiter(_this, void 0, void 0, function () {
120
+ return __generator(this, function (_a) {
121
+ switch (_a.label) {
122
+ case 0: return [4 /*yield*/, this.delete(__assign(__assign({}, options), { path: "".concat(constants_2.INTERNAL_ENDPOINT_PREFIX).concat(options.path) }))];
123
+ case 1: return [2 /*return*/, _a.sent()];
124
+ }
125
+ });
126
+ }); },
127
+ };
128
+ },
129
+ enumerable: false,
130
+ configurable: true
131
+ });
132
+ FairtrailClient.prototype.getNewInstance = function () {
133
+ var newInstance = Object.create(Object.getPrototypeOf(this));
134
+ return Object.assign(newInstance, this);
135
+ };
136
+ /**
137
+ * Makes any subsequent requests as the provided user.
138
+ * @param user can be a partial user object, only the provided fields will be used, will default to the service user for any missing fields.
139
+ */
140
+ FairtrailClient.prototype.asUser = function (user) {
141
+ if (!user) {
142
+ return this;
143
+ }
144
+ var newInstance = this.getNewInstance();
145
+ newInstance.reqUser = user;
146
+ return newInstance;
147
+ };
148
+ /**
149
+ * Makes any subsequent requests as the global user.
150
+ * @param useAsGlobal typically not used, but can be used with conditional logic to determine if the request should be made as a global user
151
+ */
152
+ FairtrailClient.prototype.asGlobal = function (useAsGlobal) {
153
+ if (useAsGlobal === void 0) { useAsGlobal = true; }
154
+ if (!useAsGlobal) {
155
+ return this;
156
+ }
157
+ var newInstance = this.getNewInstance();
158
+ newInstance.reqAsGlobal = true;
159
+ return newInstance;
160
+ };
161
+ /**
162
+ * Makes any subsequent requests as an organization manager.
163
+ * @param useAsOrganizationManagerOrOrganizationId typically not used, but can be used with conditional logic to determine if the request should be made as an organization manager. Can also be used to specify the organization id to manage.
164
+ */
165
+ FairtrailClient.prototype.asOrganizationManager = function (useAsOrganizationManagerOrOrganizationId) {
166
+ if (useAsOrganizationManagerOrOrganizationId === void 0) { useAsOrganizationManagerOrOrganizationId = true; }
167
+ if (!useAsOrganizationManagerOrOrganizationId) {
168
+ return this;
169
+ }
170
+ var newInstance = this.getNewInstance();
171
+ newInstance.reqAsOrganizationManager = true;
172
+ newInstance.reqOrganizationId =
173
+ typeof useAsOrganizationManagerOrOrganizationId === "string"
174
+ ? useAsOrganizationManagerOrOrganizationId
175
+ : undefined;
176
+ return newInstance;
177
+ };
178
+ Object.defineProperty(FairtrailClient.prototype, "serviceApiUser", {
179
+ get: function () {
180
+ return "@".concat((0, lib_1.getServiceName)());
181
+ },
182
+ enumerable: false,
183
+ configurable: true
184
+ });
185
+ FairtrailClient.prototype.getAuthHeaders = function () {
186
+ return __awaiter(this, void 0, void 0, function () {
187
+ var _a, _b, _c;
188
+ var _d, _e, _f, _g, _h, _j;
189
+ return __generator(this, function (_k) {
190
+ if (this.reqUser) {
191
+ return [2 /*return*/, (_a = {},
192
+ _a[constants_1.AUTH_USER_HEADER] = (_d = this.reqUser.userId) !== null && _d !== void 0 ? _d : this.serviceApiUser,
193
+ _a[constants_1.AUTH_ACTIVE_LOGIN_HEADER] = (_e = this.reqUser.activeLogin) !== null && _e !== void 0 ? _e : "",
194
+ _a[constants_1.AUTH_ACTIVITIES_HEADER] = Object.keys((_f = this.reqUser.activities) !== null && _f !== void 0 ? _f : []).join(","),
195
+ _a[constants_1.AUTH_ORGANIZATION_HEADER] = (_g = this.reqUser.organizationId) !== null && _g !== void 0 ? _g : "",
196
+ _a[constants_1.AUTH_CHILD_ORGANIZATIONS_HEADER] = ((_h = this.reqUser.childOrganizationIds) !== null && _h !== void 0 ? _h : []).join(","),
197
+ _a)];
198
+ }
199
+ if (this.reqAsGlobal) {
200
+ return [2 /*return*/, (_b = {},
201
+ _b[constants_1.AUTH_USER_HEADER] = this.serviceApiUser,
202
+ _b[constants_1.AUTH_ACTIVITIES_HEADER] = constants_1.GLOBAL_ACTIVITY,
203
+ _b)];
204
+ }
205
+ if (this.reqAsOrganizationManager) {
206
+ return [2 /*return*/, (_c = {},
207
+ _c[constants_1.AUTH_USER_HEADER] = this.serviceApiUser,
208
+ _c[constants_1.AUTH_ACTIVITIES_HEADER] = constants_1.CAN_MANAGE_ORGANIZATION_ACTIVITY,
209
+ _c[constants_1.AUTH_ORGANIZATION_HEADER] = (_j = this.reqOrganizationId) !== null && _j !== void 0 ? _j : "",
210
+ _c)];
211
+ }
212
+ return [2 /*return*/, {}];
213
+ });
214
+ });
215
+ };
216
+ return FairtrailClient;
217
+ }(HttpClient_1.HttpClient));
218
+ exports.FairtrailClient = FairtrailClient;
219
+ //# sourceMappingURL=FairtrailClient.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"FairtrailClient.js","sourceRoot":"","sources":["FairtrailClient.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,0CAQsB;AACtB,8BAAwC;AACxC,wDAAsE;AAEtE,2CAA0C;AAE1C;;;;GAIG;AACH;IAAqC,mCAAU;IAA/C;;QAEU,iBAAW,GAAY,KAAK,CAAC;QAC7B,8BAAwB,GAAY,KAAK,CAAC;;IAmHpD,CAAC;IAhHC,sBAAc,qCAAQ;aAAtB;YAAA,iBAsBC;YArBC,OAAO;gBACL,GAAG,EAAE,UAAO,OAAuC;;;oCAC1C,qBAAM,IAAI,CAAC,GAAG,uBAAM,OAAO,KAAE,IAAI,EAAE,UAAG,oCAAwB,SAAG,OAAO,CAAC,IAAI,CAAE,IAAG,EAAA;oCAAzF,sBAAO,SAAkF,EAAC;;;qBAC3F;gBAED,IAAI,EAAE,UAAO,OAAwC;;;oCAC5C,qBAAM,IAAI,CAAC,IAAI,uBAAM,OAAO,KAAE,IAAI,EAAE,UAAG,oCAAwB,SAAG,OAAO,CAAC,IAAI,CAAE,IAAG,EAAA;oCAA1F,sBAAO,SAAmF,EAAC;;;qBAC5F;gBAED,GAAG,EAAE,UAAO,OAAuC;;;oCAC1C,qBAAM,IAAI,CAAC,GAAG,uBAAM,OAAO,KAAE,IAAI,EAAE,UAAG,oCAAwB,SAAG,OAAO,CAAC,IAAI,CAAE,IAAG,EAAA;oCAAzF,sBAAO,SAAkF,EAAC;;;qBAC3F;gBAED,KAAK,EAAE,UAAO,OAAyC;;;oCAC9C,qBAAM,IAAI,CAAC,KAAK,uBAAM,OAAO,KAAE,IAAI,EAAE,UAAG,oCAAwB,SAAG,OAAO,CAAC,IAAI,CAAE,IAAG,EAAA;oCAA3F,sBAAO,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