UNPKG

5.44 kBJavaScriptView Raw
1"use strict";
2// Copyright 2020 Google LLC
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14Object.defineProperty(exports, "__esModule", { value: true });
15exports.Discovery = void 0;
16const fs = require("fs");
17const google_auth_library_1 = require("google-auth-library");
18const resolve = require("url");
19const util = require("util");
20const apirequest_1 = require("./apirequest");
21const endpoint_1 = require("./endpoint");
22const readFile = util.promisify(fs.readFile);
23class Discovery {
24 /**
25 * Discovery for discovering API endpoints
26 *
27 * @param options Options for discovery
28 */
29 constructor(options) {
30 this.transporter = new google_auth_library_1.DefaultTransporter();
31 this.options = options || {};
32 }
33 /**
34 * Generate and Endpoint from an endpoint schema object.
35 *
36 * @param schema The schema from which to generate the Endpoint.
37 * @return A function that creates an endpoint.
38 */
39 makeEndpoint(schema) {
40 return (options) => {
41 const ep = new endpoint_1.Endpoint(options);
42 ep.applySchema(ep, schema, schema, ep);
43 return ep;
44 };
45 }
46 /**
47 * Log output of generator. Works just like console.log
48 */
49 log(...args) {
50 if (this.options && this.options.debug) {
51 console.log(...args);
52 }
53 }
54 /**
55 * Generate all APIs and return as in-memory object.
56 * @param discoveryUrl
57 */
58 async discoverAllAPIs(discoveryUrl) {
59 const headers = this.options.includePrivate
60 ? {}
61 : { 'X-User-Ip': '0.0.0.0' };
62 const res = await this.transporter.request({
63 url: discoveryUrl,
64 headers,
65 });
66 const items = res.data.items;
67 const apis = await Promise.all(items.map(async (api) => {
68 const endpointCreator = await this.discoverAPI(api.discoveryRestUrl);
69 return { api, endpointCreator };
70 }));
71 const versionIndex = {};
72 // eslint-disable-next-line @typescript-eslint/no-explicit-any
73 const apisIndex = {};
74 for (const set of apis) {
75 if (!apisIndex[set.api.name]) {
76 versionIndex[set.api.name] = {};
77 apisIndex[set.api.name] = (options) => {
78 const type = typeof options;
79 let version;
80 if (type === 'string') {
81 version = options;
82 options = {};
83 }
84 else if (type === 'object') {
85 version = options.version;
86 delete options.version;
87 }
88 else {
89 throw new Error('Argument error: Accepts only string or object');
90 }
91 try {
92 const ep = set.endpointCreator(options, this);
93 return Object.freeze(ep); // create new & freeze
94 }
95 catch (e) {
96 throw new Error(util.format('Unable to load endpoint %s("%s"): %s', set.api.name, version, e.message));
97 }
98 };
99 }
100 versionIndex[set.api.name][set.api.version] = set.endpointCreator;
101 }
102 return apisIndex;
103 }
104 /**
105 * Generate API file given discovery URL
106 *
107 * @param apiDiscoveryUrl URL or filename of discovery doc for API
108 * @returns A promise that resolves with a function that creates the endpoint
109 */
110 async discoverAPI(apiDiscoveryUrl) {
111 if (typeof apiDiscoveryUrl === 'string') {
112 const parts = resolve.parse(apiDiscoveryUrl);
113 if (apiDiscoveryUrl && !parts.protocol) {
114 this.log('Reading from file ' + apiDiscoveryUrl);
115 const file = await readFile(apiDiscoveryUrl, { encoding: 'utf8' });
116 return this.makeEndpoint(JSON.parse(file));
117 }
118 else {
119 this.log('Requesting ' + apiDiscoveryUrl);
120 const res = await this.transporter.request({
121 url: apiDiscoveryUrl,
122 });
123 return this.makeEndpoint(res.data);
124 }
125 }
126 else {
127 const options = apiDiscoveryUrl;
128 this.log('Requesting ' + options.url);
129 const url = options.url;
130 delete options.url;
131 const parameters = {
132 options: { url, method: 'GET' },
133 requiredParams: [],
134 pathParams: [],
135 params: options,
136 context: { google: { _options: {} }, _options: {} },
137 };
138 const res = await (0, apirequest_1.createAPIRequest)(parameters);
139 return this.makeEndpoint(res.data);
140 }
141 }
142}
143exports.Discovery = Discovery;
144//# sourceMappingURL=discovery.js.map
\No newline at end of file