@omnigraph/openapi 1.0.0-alpha-3fc47d119.0 → 1.0.0-alpha-20230420181317-a95037648

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.
@@ -0,0 +1,467 @@
1
+ import { OperationTypeNode } from 'graphql';
2
+ import { dereferenceObject, handleUntitledDefinitions, resolvePath, } from 'json-machete';
3
+ import { process } from '@graphql-mesh/cross-helpers';
4
+ import { getInterpolatedHeadersFactory } from '@graphql-mesh/string-interpolation';
5
+ import { defaultImportFn, DefaultLogger, readFileOrUrl, sanitizeNameForGraphQL, } from '@graphql-mesh/utils';
6
+ import { getFieldNameFromPath } from './utils.js';
7
+ export async function getJSONSchemaOptionsFromOpenAPIOptions(name, { source, fallbackFormat, cwd, fetch: fetchFn, endpoint, schemaHeaders, operationHeaders, queryParams = {}, selectQueryOrMutationField = [], logger = new DefaultLogger('getJSONSchemaOptionsFromOpenAPIOptions'), }) {
8
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
9
+ const fieldTypeMap = {};
10
+ for (const { fieldName, type } of selectQueryOrMutationField) {
11
+ fieldTypeMap[fieldName] = type;
12
+ }
13
+ const schemaHeadersFactory = getInterpolatedHeadersFactory(schemaHeaders);
14
+ logger === null || logger === void 0 ? void 0 : logger.debug(`Fetching OpenAPI Document from ${source}`);
15
+ let oasOrSwagger = typeof source === 'string'
16
+ ? await readFileOrUrl(source, {
17
+ cwd,
18
+ fallbackFormat,
19
+ headers: schemaHeadersFactory({ env: process.env }),
20
+ fetch: fetchFn,
21
+ importFn: defaultImportFn,
22
+ logger,
23
+ })
24
+ : source;
25
+ handleUntitledDefinitions(oasOrSwagger);
26
+ oasOrSwagger = (await dereferenceObject(oasOrSwagger));
27
+ const operations = [];
28
+ let baseOperationArgTypeMap;
29
+ if (!endpoint) {
30
+ if ('servers' in oasOrSwagger) {
31
+ const serverObj = oasOrSwagger.servers[0];
32
+ endpoint = serverObj.url.split('{').join('{args.');
33
+ if (serverObj.variables) {
34
+ for (const variableName in serverObj.variables) {
35
+ const variable = serverObj.variables[variableName];
36
+ if (!variable.type) {
37
+ variable.type = 'string';
38
+ }
39
+ baseOperationArgTypeMap = baseOperationArgTypeMap || {};
40
+ baseOperationArgTypeMap[variableName] = variable;
41
+ if (variable.default) {
42
+ endpoint = endpoint.replace(`{args.${variableName}}`, `{args.${variableName}:${variable.default}}`);
43
+ }
44
+ }
45
+ }
46
+ }
47
+ if ('schemes' in oasOrSwagger && oasOrSwagger.schemes.length > 0 && oasOrSwagger.host) {
48
+ endpoint = oasOrSwagger.schemes[0] + '://' + oasOrSwagger.host;
49
+ if ('basePath' in oasOrSwagger) {
50
+ endpoint += oasOrSwagger.basePath;
51
+ }
52
+ }
53
+ }
54
+ const methodObjFieldMap = new WeakMap();
55
+ for (const relativePath in oasOrSwagger.paths) {
56
+ const pathObj = oasOrSwagger.paths[relativePath];
57
+ const pathParameters = pathObj.parameters;
58
+ for (const method in pathObj) {
59
+ if (method === 'parameters' ||
60
+ method === 'summary' ||
61
+ method === 'description' ||
62
+ method === 'servers') {
63
+ continue;
64
+ }
65
+ const methodObj = pathObj[method];
66
+ const operationConfig = {
67
+ method: method.toUpperCase(),
68
+ path: relativePath,
69
+ type: method.toUpperCase() === 'GET' ? 'query' : 'mutation',
70
+ field: methodObj.operationId && sanitizeNameForGraphQL(methodObj.operationId),
71
+ description: methodObj.description || methodObj.summary,
72
+ schemaHeaders,
73
+ operationHeaders,
74
+ responseByStatusCode: {},
75
+ ...(baseOperationArgTypeMap
76
+ ? {
77
+ argTypeMap: {
78
+ ...baseOperationArgTypeMap,
79
+ },
80
+ }
81
+ : {}),
82
+ };
83
+ operations.push(operationConfig);
84
+ methodObjFieldMap.set(methodObj, operationConfig);
85
+ let allParams;
86
+ if (methodObj.parameters && Array.isArray(methodObj.parameters)) {
87
+ allParams = [...(pathParameters || []), ...methodObj.parameters];
88
+ }
89
+ else {
90
+ allParams = {
91
+ ...(pathParameters || {}),
92
+ ...(methodObj.parameters || {}),
93
+ };
94
+ }
95
+ for (const paramObjIndex in allParams) {
96
+ const paramObj = allParams[paramObjIndex];
97
+ const argName = sanitizeNameForGraphQL(paramObj.name);
98
+ const operationArgTypeMap = (operationConfig.argTypeMap =
99
+ operationConfig.argTypeMap || {});
100
+ switch (paramObj.in) {
101
+ case 'query':
102
+ operationConfig.queryParamArgMap = operationConfig.queryParamArgMap || {};
103
+ operationConfig.queryParamArgMap[paramObj.name] = argName;
104
+ if (paramObj.name in queryParams) {
105
+ paramObj.required = false;
106
+ if (!((_a = paramObj.schema) === null || _a === void 0 ? void 0 : _a.default)) {
107
+ paramObj.schema = paramObj.schema || {
108
+ type: 'string',
109
+ };
110
+ paramObj.schema.default = queryParams[paramObj.name];
111
+ }
112
+ }
113
+ if ('explode' in paramObj) {
114
+ operationConfig.queryStringOptionsByParam =
115
+ operationConfig.queryStringOptionsByParam || {};
116
+ operationConfig.queryStringOptionsByParam[paramObj.name] =
117
+ operationConfig.queryStringOptionsByParam[paramObj.name] || {};
118
+ if (paramObj.explode) {
119
+ operationConfig.queryStringOptionsByParam[paramObj.name].arrayFormat = 'repeat';
120
+ operationConfig.queryStringOptionsByParam[paramObj.name].destructObject = true;
121
+ }
122
+ else {
123
+ if (paramObj.style === 'form') {
124
+ operationConfig.queryStringOptionsByParam[paramObj.name].arrayFormat = 'comma';
125
+ }
126
+ else {
127
+ logger.warn(`Other styles including ${paramObj.style} of query parameters are not supported yet.`);
128
+ }
129
+ }
130
+ }
131
+ break;
132
+ case 'path': {
133
+ // If it is in the path, let JSON Schema handler put it
134
+ operationConfig.path = operationConfig.path.replace(`{${paramObj.name}}`, `{args.${argName}}`);
135
+ break;
136
+ }
137
+ case 'header': {
138
+ operationConfig.headers = operationConfig.headers || {};
139
+ if (typeof operationHeaders === 'object' && operationHeaders[paramObj.name]) {
140
+ paramObj.required = false;
141
+ const valueFromGlobal = operationHeaders[paramObj.name];
142
+ if (!valueFromGlobal.includes('{')) {
143
+ if (paramObj.schema) {
144
+ paramObj.schema.default = valueFromGlobal;
145
+ }
146
+ }
147
+ else {
148
+ if ((_b = paramObj.schema) === null || _b === void 0 ? void 0 : _b.default) {
149
+ delete paramObj.schema.default;
150
+ }
151
+ }
152
+ }
153
+ if (typeof operationHeaders === 'function') {
154
+ paramObj.required = false;
155
+ if ((_c = paramObj.schema) === null || _c === void 0 ? void 0 : _c.default) {
156
+ delete paramObj.schema.default;
157
+ }
158
+ }
159
+ let defaultValueSuffix = '';
160
+ if ((_d = paramObj.schema) === null || _d === void 0 ? void 0 : _d.default) {
161
+ defaultValueSuffix = `:${paramObj.schema.default}`;
162
+ }
163
+ operationConfig.headers[paramObj.name] = `{args.${argName}${defaultValueSuffix}}`;
164
+ break;
165
+ }
166
+ case 'cookie': {
167
+ operationConfig.headers = operationConfig.headers || {};
168
+ operationConfig.headers.cookie = operationConfig.headers.cookie || '';
169
+ const cookieParams = operationConfig.headers.cookie.split(' ').filter(c => !!c);
170
+ cookieParams.push(`${paramObj.name}={args.${argName}};`);
171
+ operationConfig.headers.cookie = `${cookieParams.join(' ')}`;
172
+ break;
173
+ }
174
+ case 'body':
175
+ if (paramObj.schema && Object.keys(paramObj.schema).length > 0) {
176
+ operationConfig.requestSchema = paramObj.schema;
177
+ }
178
+ if (paramObj.example) {
179
+ operationConfig.requestSample = paramObj.example;
180
+ }
181
+ if (paramObj.examples) {
182
+ operationConfig.requestSample = Object.values(paramObj.examples)[0];
183
+ }
184
+ break;
185
+ }
186
+ operationArgTypeMap[argName] =
187
+ paramObj.schema || ((_f = (_e = paramObj.content) === null || _e === void 0 ? void 0 : _e['application/json']) === null || _f === void 0 ? void 0 : _f.schema) || paramObj;
188
+ if (!operationArgTypeMap[argName].title) {
189
+ operationArgTypeMap[argName].name = paramObj.name;
190
+ }
191
+ if (!operationArgTypeMap[argName].description) {
192
+ operationArgTypeMap[argName].description = paramObj.description;
193
+ }
194
+ if (paramObj.required) {
195
+ operationArgTypeMap[argName].nullable = false;
196
+ }
197
+ if (!('type' in paramObj) &&
198
+ !paramObj.schema &&
199
+ !paramObj.content &&
200
+ !paramObj.example &&
201
+ !paramObj.examples) {
202
+ operationArgTypeMap[argName].type = 'string';
203
+ }
204
+ }
205
+ if ('requestBody' in methodObj) {
206
+ const requestBodyObj = methodObj.requestBody;
207
+ if ('content' in requestBodyObj) {
208
+ const contentKey = Object.keys(requestBodyObj.content)[0];
209
+ const contentSchema = (_g = requestBodyObj.content[contentKey]) === null || _g === void 0 ? void 0 : _g.schema;
210
+ if (contentSchema && Object.keys(contentSchema).length > 0) {
211
+ operationConfig.requestSchema = contentSchema;
212
+ }
213
+ const examplesObj = (_h = requestBodyObj.content[contentKey]) === null || _h === void 0 ? void 0 : _h.examples;
214
+ if (examplesObj) {
215
+ operationConfig.requestSample = Object.values(examplesObj)[0];
216
+ }
217
+ if (!((_j = operationConfig.headers) === null || _j === void 0 ? void 0 : _j['Content-Type']) && typeof contentKey === 'string') {
218
+ operationConfig.headers = operationConfig.headers || {};
219
+ operationConfig.headers['Content-Type'] = contentKey;
220
+ }
221
+ }
222
+ }
223
+ const responseByStatusCode = operationConfig.responseByStatusCode;
224
+ // Handling multiple response types
225
+ for (const responseKey in methodObj.responses) {
226
+ const responseObj = methodObj.responses[responseKey];
227
+ let schemaObj;
228
+ if ('consumes' in methodObj) {
229
+ operationConfig.headers = operationConfig.headers || {};
230
+ operationConfig.headers['Content-Type'] = methodObj.consumes.join(', ');
231
+ }
232
+ if ('produces' in methodObj) {
233
+ operationConfig.headers = operationConfig.headers || {};
234
+ operationConfig.headers.Accept = methodObj.produces.join(', ');
235
+ }
236
+ if ('content' in responseObj) {
237
+ const responseObjForStatusCode = {
238
+ oneOf: [],
239
+ };
240
+ let allMimeTypes = [];
241
+ if (typeof operationHeaders === 'object') {
242
+ const acceptFromOperationHeader = operationHeaders.accept || operationHeaders.Accept;
243
+ if (acceptFromOperationHeader) {
244
+ allMimeTypes = [acceptFromOperationHeader];
245
+ }
246
+ }
247
+ if (allMimeTypes.length === 0) {
248
+ allMimeTypes = Object.keys(responseObj.content);
249
+ }
250
+ const jsonLikeMimeTypes = allMimeTypes.filter(c => c !== '*/*' && c.toString().includes('json'));
251
+ const mimeTypes = jsonLikeMimeTypes.length > 0 ? jsonLikeMimeTypes : allMimeTypes;
252
+ // If we have a better accept header, overwrite User's choice
253
+ if ((!((_k = operationConfig.headers) === null || _k === void 0 ? void 0 : _k.accept) && !((_l = operationConfig.headers) === null || _l === void 0 ? void 0 : _l.Accept)) ||
254
+ mimeTypes.length === 1) {
255
+ operationConfig.headers = operationConfig.headers || {};
256
+ if (operationConfig.headers.Accept) {
257
+ delete operationConfig.headers.Accept;
258
+ }
259
+ operationConfig.headers.accept =
260
+ jsonLikeMimeTypes.length > 0
261
+ ? jsonLikeMimeTypes.join(',')
262
+ : allMimeTypes[0].toString();
263
+ }
264
+ for (const contentKey in responseObj.content) {
265
+ if (!mimeTypes.includes(contentKey)) {
266
+ continue;
267
+ }
268
+ schemaObj = responseObj.content[contentKey].schema;
269
+ if (schemaObj && Object.keys(schemaObj).length > 0) {
270
+ responseObjForStatusCode.oneOf.push(schemaObj);
271
+ }
272
+ else if (contentKey.toString().startsWith('text')) {
273
+ responseObjForStatusCode.oneOf.push({ type: 'string' });
274
+ }
275
+ else {
276
+ const examplesObj = responseObj.content[contentKey].examples;
277
+ if (examplesObj) {
278
+ let examples = Object.values(examplesObj);
279
+ if (contentKey.includes('json')) {
280
+ examples = examples.map(example => {
281
+ if (typeof example === 'string') {
282
+ return JSON.parse(example);
283
+ }
284
+ return example;
285
+ });
286
+ }
287
+ responseObjForStatusCode.oneOf.push({
288
+ examples,
289
+ });
290
+ }
291
+ let example = responseObj.content[contentKey].example;
292
+ if (example) {
293
+ if (typeof example === 'string' && contentKey.includes('json')) {
294
+ example = JSON.parse(example);
295
+ }
296
+ responseObjForStatusCode.oneOf.push({
297
+ examples: [example],
298
+ });
299
+ }
300
+ }
301
+ }
302
+ if (responseObjForStatusCode.oneOf.length === 1) {
303
+ responseByStatusCode[responseKey] = responseByStatusCode[responseKey] || {};
304
+ responseByStatusCode[responseKey].responseSchema = responseObjForStatusCode.oneOf[0];
305
+ }
306
+ else if (responseObjForStatusCode.oneOf.length > 1) {
307
+ responseByStatusCode[responseKey] = responseByStatusCode[responseKey] || {};
308
+ responseByStatusCode[responseKey].responseSchema = responseObjForStatusCode;
309
+ }
310
+ }
311
+ else if ('schema' in responseObj) {
312
+ schemaObj = responseObj.schema;
313
+ if (schemaObj && Object.keys(schemaObj).length > 0) {
314
+ responseByStatusCode[responseKey] = responseByStatusCode[responseKey] || {};
315
+ responseByStatusCode[responseKey].responseSchema = schemaObj;
316
+ }
317
+ }
318
+ else if ('examples' in responseObj) {
319
+ const examples = Object.values(responseObj.examples);
320
+ responseByStatusCode[responseKey] = responseByStatusCode[responseKey] || {};
321
+ let example = examples[0];
322
+ if (typeof example === 'string') {
323
+ try {
324
+ // Parse if possible
325
+ example = JSON.parse(example);
326
+ }
327
+ catch (e) {
328
+ // Do nothing
329
+ }
330
+ }
331
+ responseByStatusCode[responseKey].responseSample = example;
332
+ }
333
+ else if (responseKey.toString() === '204') {
334
+ responseByStatusCode[responseKey] = responseByStatusCode[responseKey] || {};
335
+ responseByStatusCode[responseKey].responseSchema = {
336
+ type: 'null',
337
+ description: responseObj.description,
338
+ };
339
+ }
340
+ if ('links' in responseObj) {
341
+ const dereferencedLinkObj = await dereferenceObject({
342
+ links: responseObj.links,
343
+ }, {
344
+ cwd,
345
+ root: oasOrSwagger,
346
+ fetchFn,
347
+ logger,
348
+ headers: schemaHeaders,
349
+ });
350
+ responseByStatusCode[responseKey].links = responseByStatusCode[responseKey].links || {};
351
+ for (const linkName in dereferencedLinkObj.links) {
352
+ const linkObj = responseObj.links[linkName];
353
+ let args;
354
+ if (linkObj.parameters) {
355
+ args = {};
356
+ for (const parameterName in linkObj.parameters) {
357
+ const parameterExp = linkObj.parameters[parameterName];
358
+ const sanitizedParamName = sanitizeNameForGraphQL(parameterName);
359
+ if (typeof parameterExp === 'string') {
360
+ args[sanitizedParamName] = parameterExp.startsWith('$')
361
+ ? `{root.${parameterExp}}`
362
+ : parameterExp.split('$').join('root.$');
363
+ }
364
+ else {
365
+ args[sanitizedParamName] = parameterExp;
366
+ }
367
+ }
368
+ }
369
+ const sanitizedLinkName = sanitizeNameForGraphQL(linkName);
370
+ if ('operationRef' in linkObj) {
371
+ const [externalPath, ref] = linkObj.operationRef.split('#');
372
+ if (externalPath) {
373
+ logger.debug(`Skipping external operation reference ${linkObj.operationRef}\n Use additionalTypeDefs and additionalResolvers instead.`);
374
+ }
375
+ else {
376
+ const actualOperation = resolvePath(ref, oasOrSwagger);
377
+ responseByStatusCode[responseKey].links[sanitizedLinkName] = {
378
+ get fieldName() {
379
+ const linkOperationConfig = methodObjFieldMap.get(actualOperation);
380
+ return linkOperationConfig.field;
381
+ },
382
+ args,
383
+ description: linkObj.description,
384
+ };
385
+ }
386
+ }
387
+ else if ('operationId' in linkObj) {
388
+ responseByStatusCode[responseKey].links[sanitizedLinkName] = {
389
+ fieldName: sanitizeNameForGraphQL(linkObj.operationId),
390
+ args,
391
+ description: linkObj.description,
392
+ };
393
+ }
394
+ }
395
+ }
396
+ if (!operationConfig.field) {
397
+ methodObj.operationId = getFieldNameFromPath(relativePath, method, schemaObj === null || schemaObj === void 0 ? void 0 : schemaObj.$resolvedRef);
398
+ // Operation ID might not be avaiable so let's generate field name from path and response type schema
399
+ operationConfig.field = sanitizeNameForGraphQL(methodObj.operationId);
400
+ }
401
+ // Give a better name to the request input object
402
+ if (typeof operationConfig.requestSchema === 'object' &&
403
+ !operationConfig.requestSchema.title) {
404
+ operationConfig.requestSchema.title = operationConfig.field + '_request';
405
+ }
406
+ }
407
+ if ('callbacks' in methodObj) {
408
+ for (const callbackKey in methodObj.callbacks) {
409
+ const callbackObj = methodObj.callbacks[callbackKey];
410
+ for (const callbackUrlRefKey in callbackObj) {
411
+ if (callbackUrlRefKey.startsWith('$')) {
412
+ continue;
413
+ }
414
+ const pubsubTopicSuffix = callbackUrlRefKey
415
+ .split('$request.query')
416
+ .join('args')
417
+ .split('$request.body#/')
418
+ .join('args.')
419
+ .split('$response.body#/')
420
+ .join('args.');
421
+ const callbackOperationConfig = {
422
+ type: OperationTypeNode.SUBSCRIPTION,
423
+ field: '',
424
+ pubsubTopic: '',
425
+ };
426
+ const callbackUrlObj = callbackObj[callbackUrlRefKey];
427
+ for (const method in callbackUrlObj) {
428
+ const callbackOperation = callbackUrlObj[method];
429
+ callbackOperationConfig.pubsubTopic = `webhook:${method}:${pubsubTopicSuffix}`;
430
+ callbackOperationConfig.field = callbackOperation.operationId;
431
+ callbackOperationConfig.description =
432
+ callbackOperation.description || callbackOperation.summary;
433
+ const requestBodyContents = (_m = callbackOperation.requestBody) === null || _m === void 0 ? void 0 : _m.content;
434
+ if (requestBodyContents) {
435
+ callbackOperationConfig.responseSchema = requestBodyContents[Object.keys(requestBodyContents)[0]].schema;
436
+ }
437
+ const responses = callbackOperation.responses;
438
+ if (responses) {
439
+ const response = responses[Object.keys(responses)[0]];
440
+ if (response) {
441
+ const responseContents = response.content;
442
+ if (responseContents) {
443
+ callbackOperationConfig.requestSchema = responseContents[Object.keys(responseContents)[0]].schema;
444
+ }
445
+ }
446
+ }
447
+ }
448
+ callbackOperationConfig.field =
449
+ callbackOperationConfig.field || sanitizeNameForGraphQL(callbackKey);
450
+ operations.push(callbackOperationConfig);
451
+ }
452
+ }
453
+ }
454
+ if (fieldTypeMap[operationConfig.field]) {
455
+ operationConfig.type = fieldTypeMap[operationConfig.field];
456
+ }
457
+ }
458
+ }
459
+ return {
460
+ operations,
461
+ endpoint,
462
+ cwd,
463
+ fetch: fetchFn,
464
+ schemaHeaders,
465
+ operationHeaders,
466
+ };
467
+ }
package/esm/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { loadGraphQLSchemaFromOpenAPI as default } from './loadGraphQLSchemaFromOpenAPI.js';
2
+ export * from './loadGraphQLSchemaFromOpenAPI.js';
3
+ export { getJSONSchemaOptionsFromOpenAPIOptions } from './getJSONSchemaOptionsFromOpenAPIOptions.js';
@@ -0,0 +1,23 @@
1
+ import { loadGraphQLSchemaFromJSONSchemas, loadNonExecutableGraphQLSchemaFromJSONSchemas, } from '@omnigraph/json-schema';
2
+ import { getJSONSchemaOptionsFromOpenAPIOptions } from './getJSONSchemaOptionsFromOpenAPIOptions.js';
3
+ /**
4
+ * Creates a local GraphQLSchema instance from a OpenAPI Document.
5
+ * Everytime this function is called, the OpenAPI file and its dependencies will be resolved on runtime.
6
+ * If you want to avoid this, use `createBundle` function to create a bundle once and save it to a storage
7
+ * then load it with `loadGraphQLSchemaFromBundle`.
8
+ */
9
+ export async function loadGraphQLSchemaFromOpenAPI(name, options) {
10
+ const extraJSONSchemaOptions = await getJSONSchemaOptionsFromOpenAPIOptions(name, options);
11
+ return loadGraphQLSchemaFromJSONSchemas(name, {
12
+ ...options,
13
+ ...extraJSONSchemaOptions,
14
+ });
15
+ }
16
+ export async function loadNonExecutableGraphQLSchemaFromOpenAPI(name, options) {
17
+ const extraJSONSchemaOptions = await getJSONSchemaOptionsFromOpenAPIOptions(name, options);
18
+ return loadNonExecutableGraphQLSchemaFromJSONSchemas(name, {
19
+ ...options,
20
+ ...extraJSONSchemaOptions,
21
+ });
22
+ }
23
+ export { processDirectives } from '@omnigraph/json-schema';
package/esm/types.js ADDED
File without changes
package/esm/utils.js ADDED
@@ -0,0 +1,40 @@
1
+ import { camelCase } from 'change-case';
2
+ export function getFieldNameFromPath(path, method, responseTypeSchemaRef) {
3
+ // Replace identifiers with "by"
4
+ path = path.split('{').join('by_').split('}').join('');
5
+ const [actualPartsStr, allQueryPartsStr] = path.split('?');
6
+ const actualParts = actualPartsStr.split('/').filter(Boolean);
7
+ let fieldNameWithoutMethod = actualParts.join('_');
8
+ // If path doesn't give any field name without identifiers, we can use the return type with HTTP Method name
9
+ if ((!fieldNameWithoutMethod || fieldNameWithoutMethod.startsWith('by')) &&
10
+ responseTypeSchemaRef) {
11
+ const refArr = responseTypeSchemaRef.split('/');
12
+ // lowercase looks better in the schema
13
+ const prefix = camelCase(refArr[refArr.length - 1]);
14
+ if (fieldNameWithoutMethod) {
15
+ fieldNameWithoutMethod = prefix + '_' + fieldNameWithoutMethod;
16
+ }
17
+ else {
18
+ fieldNameWithoutMethod = prefix;
19
+ }
20
+ }
21
+ if (fieldNameWithoutMethod.startsWith('by_')) {
22
+ fieldNameWithoutMethod = fieldNameWithoutMethod.replace('by_', '');
23
+ }
24
+ if (allQueryPartsStr) {
25
+ const queryParts = allQueryPartsStr.split('&');
26
+ for (const queryPart of queryParts) {
27
+ const [queryName] = queryPart.split('=');
28
+ fieldNameWithoutMethod += '_' + 'by' + '_' + queryName;
29
+ }
30
+ }
31
+ // get_ doesn't look good in field names
32
+ const methodPrefix = method.toLowerCase();
33
+ if (methodPrefix === 'get') {
34
+ return fieldNameWithoutMethod;
35
+ }
36
+ if (fieldNameWithoutMethod) {
37
+ return methodPrefix + '_' + fieldNameWithoutMethod;
38
+ }
39
+ return methodPrefix;
40
+ }
package/package.json CHANGED
@@ -1,20 +1,20 @@
1
1
  {
2
2
  "name": "@omnigraph/openapi",
3
- "version": "1.0.0-alpha-3fc47d119.0",
3
+ "version": "1.0.0-alpha-20230420181317-a95037648",
4
4
  "sideEffects": false,
5
5
  "peerDependencies": {
6
- "@graphql-mesh/types": "0.79.0-alpha-3fc47d119.0",
7
- "@graphql-mesh/utils": "1.0.0-alpha-3fc47d119.0",
8
- "graphql": "*"
6
+ "@graphql-mesh/cross-helpers": "^0.3.4",
7
+ "@graphql-mesh/types": "1.0.0-alpha-20230420181317-a95037648",
8
+ "@graphql-mesh/utils": "1.0.0-alpha-20230420181317-a95037648",
9
+ "graphql": "*",
10
+ "tslib": "^2.4.0"
9
11
  },
10
12
  "dependencies": {
11
- "@graphql-mesh/cross-helpers": "0.2.0",
12
- "@graphql-mesh/string-interpolation": "0.3.0",
13
- "@omnigraph/json-schema": "1.0.0-alpha-3fc47d119.0",
13
+ "@graphql-mesh/string-interpolation": "0.4.4",
14
+ "@omnigraph/json-schema": "1.0.0-alpha-20230420181317-a95037648",
14
15
  "change-case": "4.1.2",
15
- "json-machete": "1.0.0-alpha-3fc47d119.0",
16
- "openapi-types": "12.0.0",
17
- "tslib": "^2.4.0"
16
+ "json-machete": "1.0.0-alpha-20230420181317-a95037648",
17
+ "openapi-types": "12.1.0"
18
18
  },
19
19
  "repository": {
20
20
  "type": "git",
@@ -22,21 +22,28 @@
22
22
  "directory": "packages/loaders/openapi"
23
23
  },
24
24
  "license": "MIT",
25
- "main": "index.js",
26
- "module": "index.mjs",
27
- "typings": "index.d.ts",
25
+ "main": "cjs/index.js",
26
+ "module": "esm/index.js",
27
+ "typings": "typings/index.d.ts",
28
28
  "typescript": {
29
- "definition": "index.d.ts"
29
+ "definition": "typings/index.d.ts"
30
30
  },
31
+ "type": "module",
31
32
  "exports": {
32
33
  ".": {
33
- "require": "./index.js",
34
- "import": "./index.mjs"
35
- },
36
- "./*": {
37
- "require": "./*.js",
38
- "import": "./*.mjs"
34
+ "require": {
35
+ "types": "./typings/index.d.cts",
36
+ "default": "./cjs/index.js"
37
+ },
38
+ "import": {
39
+ "types": "./typings/index.d.ts",
40
+ "default": "./esm/index.js"
41
+ },
42
+ "default": {
43
+ "types": "./typings/index.d.ts",
44
+ "default": "./esm/index.js"
45
+ }
39
46
  },
40
47
  "./package.json": "./package.json"
41
48
  }
42
- }
49
+ }
@@ -0,0 +1,26 @@
1
+ /// <reference types="@cloudflare/workers-types" />
2
+ import { OpenAPIV2, OpenAPIV3 } from 'openapi-types';
3
+ import { Logger } from '@graphql-mesh/types';
4
+ import { JSONSchemaOperationConfig, OperationHeadersConfiguration } from '@omnigraph/json-schema';
5
+ import { OpenAPILoaderSelectQueryOrMutationFieldConfig } from './types.cjs';
6
+ interface GetJSONSchemaOptionsFromOpenAPIOptionsParams {
7
+ source: OpenAPIV3.Document | OpenAPIV2.Document | string;
8
+ fallbackFormat?: 'json' | 'yaml' | 'js' | 'ts';
9
+ cwd?: string;
10
+ fetch?: WindowOrWorkerGlobalScope['fetch'];
11
+ endpoint?: string;
12
+ schemaHeaders?: Record<string, string>;
13
+ operationHeaders?: OperationHeadersConfiguration;
14
+ queryParams?: Record<string, any>;
15
+ selectQueryOrMutationField?: OpenAPILoaderSelectQueryOrMutationFieldConfig[];
16
+ logger?: Logger;
17
+ }
18
+ export declare function getJSONSchemaOptionsFromOpenAPIOptions(name: string, { source, fallbackFormat, cwd, fetch: fetchFn, endpoint, schemaHeaders, operationHeaders, queryParams, selectQueryOrMutationField, logger, }: GetJSONSchemaOptionsFromOpenAPIOptionsParams): Promise<{
19
+ operations: JSONSchemaOperationConfig[];
20
+ endpoint: string;
21
+ cwd: string;
22
+ fetch: (input: RequestInfo | URL, init?: RequestInit<CfProperties<unknown>>) => Promise<Response>;
23
+ schemaHeaders: Record<string, string>;
24
+ operationHeaders: OperationHeadersConfiguration;
25
+ }>;
26
+ export {};
@@ -0,0 +1,26 @@
1
+ /// <reference types="@cloudflare/workers-types" />
2
+ import { OpenAPIV2, OpenAPIV3 } from 'openapi-types';
3
+ import { Logger } from '@graphql-mesh/types';
4
+ import { JSONSchemaOperationConfig, OperationHeadersConfiguration } from '@omnigraph/json-schema';
5
+ import { OpenAPILoaderSelectQueryOrMutationFieldConfig } from './types.js';
6
+ interface GetJSONSchemaOptionsFromOpenAPIOptionsParams {
7
+ source: OpenAPIV3.Document | OpenAPIV2.Document | string;
8
+ fallbackFormat?: 'json' | 'yaml' | 'js' | 'ts';
9
+ cwd?: string;
10
+ fetch?: WindowOrWorkerGlobalScope['fetch'];
11
+ endpoint?: string;
12
+ schemaHeaders?: Record<string, string>;
13
+ operationHeaders?: OperationHeadersConfiguration;
14
+ queryParams?: Record<string, any>;
15
+ selectQueryOrMutationField?: OpenAPILoaderSelectQueryOrMutationFieldConfig[];
16
+ logger?: Logger;
17
+ }
18
+ export declare function getJSONSchemaOptionsFromOpenAPIOptions(name: string, { source, fallbackFormat, cwd, fetch: fetchFn, endpoint, schemaHeaders, operationHeaders, queryParams, selectQueryOrMutationField, logger, }: GetJSONSchemaOptionsFromOpenAPIOptionsParams): Promise<{
19
+ operations: JSONSchemaOperationConfig[];
20
+ endpoint: string;
21
+ cwd: string;
22
+ fetch: (input: RequestInfo | URL, init?: RequestInit<CfProperties<unknown>>) => Promise<Response>;
23
+ schemaHeaders: Record<string, string>;
24
+ operationHeaders: OperationHeadersConfiguration;
25
+ }>;
26
+ export {};