sofa-api 0.5.0 → 0.7.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.
Files changed (55) hide show
  1. package/{dist/ast.d.ts → ast.d.ts} +7 -7
  2. package/{dist/common.d.ts → common.d.ts} +2 -1
  3. package/express.d.ts +5 -0
  4. package/index.cjs.js +1058 -0
  5. package/{dist/index.d.ts → index.d.ts} +6 -6
  6. package/index.esm.js +1050 -0
  7. package/{dist/logger.d.ts → logger.d.ts} +1 -1
  8. package/{dist/open-api → open-api}/index.d.ts +14 -12
  9. package/{dist/open-api → open-api}/interfaces.d.ts +325 -325
  10. package/{dist/open-api → open-api}/operations.d.ts +7 -7
  11. package/{dist/open-api → open-api}/types.d.ts +3 -3
  12. package/{dist/open-api → open-api}/utils.d.ts +2 -2
  13. package/{dist/operation.d.ts → operation.d.ts} +12 -12
  14. package/package.json +23 -71
  15. package/{dist/parse.d.ts → parse.d.ts} +6 -6
  16. package/{dist/sofa.d.ts → sofa.d.ts} +33 -33
  17. package/{dist/subscriptions.d.ts → subscriptions.d.ts} +38 -38
  18. package/{dist/types.d.ts → types.d.ts} +17 -17
  19. package/.DS_Store +0 -0
  20. package/.git/logs/refs/remotes/origin/changelog +0 -1
  21. package/.git/refs/remotes/origin/changelog +0 -1
  22. package/CHANGELOG.md +0 -30
  23. package/LICENSE +0 -21
  24. package/README.md +0 -276
  25. package/dist/ast.js +0 -16
  26. package/dist/ast.js.map +0 -1
  27. package/dist/common.js +0 -8
  28. package/dist/common.js.map +0 -1
  29. package/dist/express.d.ts +0 -5
  30. package/dist/express.js +0 -226
  31. package/dist/express.js.map +0 -1
  32. package/dist/index.js +0 -13
  33. package/dist/index.js.map +0 -1
  34. package/dist/logger.js +0 -8
  35. package/dist/logger.js.map +0 -1
  36. package/dist/open-api/index.js +0 -67
  37. package/dist/open-api/index.js.map +0 -1
  38. package/dist/open-api/interfaces.js +0 -3
  39. package/dist/open-api/interfaces.js.map +0 -1
  40. package/dist/open-api/operations.js +0 -112
  41. package/dist/open-api/operations.js.map +0 -1
  42. package/dist/open-api/types.js +0 -50
  43. package/dist/open-api/types.js.map +0 -1
  44. package/dist/open-api/utils.js +0 -29
  45. package/dist/open-api/utils.js.map +0 -1
  46. package/dist/operation.js +0 -258
  47. package/dist/operation.js.map +0 -1
  48. package/dist/parse.js +0 -46
  49. package/dist/parse.js.map +0 -1
  50. package/dist/sofa.js +0 -90
  51. package/dist/sofa.js.map +0 -1
  52. package/dist/subscriptions.js +0 -174
  53. package/dist/subscriptions.js.map +0 -1
  54. package/dist/types.js +0 -3
  55. package/dist/types.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/open-api/index.ts"],"names":[],"mappings":";;AAAA,qCAKiB;AACjB,+BAA+B;AAC/B,2BAAmC;AAEnC,mCAAoD;AACpD,6CAAsD;AAItD,SAAgB,OAAO,CAAC,EACtB,MAAM,EACN,IAAI,GAIL;IACC,MAAM,KAAK,GAAG,MAAM,CAAC,UAAU,EAAE,CAAC;IAClC,MAAM,OAAO,GAAQ;QACnB,OAAO,EAAE,OAAO;QAChB,IAAI;QACJ,KAAK,EAAE,EAAE;QACT,UAAU,EAAE;YACV,OAAO,EAAE,EAAE;SACZ;KACF,CAAC;IAEF,KAAK,MAAM,QAAQ,IAAI,KAAK,EAAE;QAC5B,MAAM,IAAI,GAAG,KAAK,CAAC,QAAQ,CAAC,CAAC;QAE7B,IACE,CAAC,sBAAY,CAAC,IAAI,CAAC,IAAI,2BAAiB,CAAC,IAAI,CAAC,CAAC;YAC/C,CAAC,6BAAmB,CAAC,IAAI,CAAC,EAC1B;YACA,OAAO,CAAC,UAAW,CAAC,OAAQ,CAAC,QAAQ,CAAC,GAAG,iCAAyB,CAAC,IAAI,CAAC,CAAC;SAC1E;KACF;IAED,OAAO;QACL,QAAQ,CACN,IAAe,EACf,MAEC;YAED,MAAM,QAAQ,GAAG,CAAC,MAAM,IAAI,M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D;iBAAM;gBACL,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;aACxD;QACH,CAAC;KACF,CAAC;AACJ,CAAC;AA1ED,0BA0EC;AAED,SAAS,WAAW,CAAC,QAAgB,EAAE,QAAgB;IACrD,kBAAa,CAAC,QAAQ,EAAE,QAAQ,EAAE;QAChC,QAAQ,EAAE,OAAO;KAClB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n GraphQLSchema,\n isObjectType,\n isInputObjectType,\n isIntrospectionType,\n} from 'graphql';\nimport * as YAML from 'yamljs';\nimport { writeFileSync } from 'fs';\n\nimport { buildSchemaObjectFromType } from './types';\nimport { buildPathFromOperation } from './operations';\nimport { RouteInfo } from '../types';\nimport { OpenAPI } from './interfaces';\n\nexport function OpenAPI({\n schema,\n info,\n}: {\n schema: GraphQLSchema;\n info: Record<string, any>;\n}) {\n const types = schema.getTypeMap();\n const swagger: any = {\n openapi: '3.0.0',\n info,\n paths: {},\n components: {\n schemas: {},\n },\n };\n\n for (const typeName in types) {\n const type = types[typeName];\n\n if (\n (isObjectType(type) || isInputObjectType(type)) &&\n !isIntrospectionType(type)\n ) {\n swagger.components!.schemas![typeName] = buildSchemaObjectFromType(type);\n }\n }\n\n return {\n addRoute(\n info: RouteInfo,\n config?: {\n basePath?: string;\n }\n ) {\n const basePath = (config && config.basePath) || '';\n const path =\n basePath +\n info.path.replace(\n /\\:[a-z0-9]+\\w/i,\n param => `{${param.replace(':', '')}}`\n );\n\n if (!swagger.paths[path]) {\n swagger.paths[path] = {};\n }\n\n swagger.paths[path][info.method.toLowerCase()] = buildPathFromOperation({\n url: path,\n operation: info.document,\n schema,\n useRequestBody: ['POST', 'PUT', 'PATCH'].includes(info.method),\n });\n\n swagger.components.schemas.ID = {\n type: 'string',\n };\n },\n get() {\n return swagger;\n },\n save(filepath: string) {\n const isJSON = /\\.json$/i;\n const isYAML = /.ya?ml$/i;\n\n if (isJSON.test(filepath)) {\n writeOutput(filepath, JSON.stringify(swagger, null, 2));\n } else if (isYAML.test(filepath)) {\n writeOutput(filepath, YAML.stringify(swagger, Infinity));\n } else {\n throw new Error('We only support JSON and YAML files');\n }\n },\n };\n}\n\nfunction writeOutput(filepath: string, contents: string) {\n writeFileSync(filepath, contents, {\n encoding: 'utf-8',\n });\n}\n"]}
@@ -1,3 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- //# sourceMappingURL=interfaces.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"interfaces.js","sourceRoot":"","sources":["../../src/open-api/interfaces.ts"],"names":[],"mappings":"","sourcesContent":["type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;\n\nexport namespace OpenAPI {\n export interface Contact {\n /**\n * The identifying name of the contact person/organization.\n */\n name?: string;\n /**\n * The URL pointing to the contact information. MUST be in the format of a URL.\n */\n url?: string;\n /**\n * The email address of the contact person/organization. MUST be in the format of an email address.\n */\n email?: string;\n }\n\n export interface License {\n /**\n * The license name used for the API.\n */\n name: string;\n /**\n * A URL to the license used for the API. MUST be in the format of a URL.\n */\n url?: string;\n }\n\n export interface Info {\n /**\n * The title of the application.\n */\n title: string;\n /**\n * A short description of the application. CommonMark syntax MAY be used for rich text representation.\n */\n description?: string;\n /**\n * A URL to the Terms of Service for the API. MUST be in the format of a URL.\n */\n termsOfService?: string;\n /**\n * The contact information for the exposed API.\n */\n contact?: Contact;\n /**\n * The license information for the exposed API.\n */\n license?: License;\n /**\n * The version of the OpenAPI document (which is distinct from the OpenAPI Specification version or the API implementation version).\n */\n version: string;\n }\n\n export interface Reference {\n /**\n * The reference string.\n */\n $ref: string;\n }\n\n export interface Parameter {\n /**\n * The name of the parameter. Parameter names are case sensitive.\n * - If in is \"path\", the name field MUST correspond to the associated path segment from the path field in the Paths Object. See Path Templating for further information.\n * - If in is \"header\" and the name field is \"Accept\", \"Content-Type\" or \"Authorization\", the parameter definition SHALL be ignored.\n * - For all other cases, the name corresponds to the parameter name used by the in property\n */\n name: string;\n /**\n * The location of the parameter. Possible values are \"query\", \"header\", \"path\" or \"cookie\".\n */\n in: 'query' | 'header' | 'path' | 'cookie';\n /**\n * A brief description of the parameter. This could contain examples of use. CommonMark syntax MAY be used for rich text representation.\n */\n description?: string;\n /**\n * Determines whether this parameter is mandatory. If the parameter location is \"path\", this property is REQUIRED and its value MUST be true. Otherwise, the property MAY be included and its default value is false.\n */\n required: boolean;\n /**\n * Specifies that a parameter is deprecated and SHOULD be transitioned out of usage. Default value is false.\n */\n deprecated?: boolean;\n /**\n * Sets the ability to pass empty-valued parameters. This is valid only for query parameters and allows sending a parameter with an empty value. Default value is false. If style is used, and if behavior is n/a (cannot be serialized), the value of allowEmptyValue SHALL be ignored. Use of this property is NOT RECOMMENDED, as it is likely to be removed in a later revision.\n */\n allowEmptyValue?: boolean;\n schema?: Reference | Schema;\n }\n\n export interface RequestBody {\n /**\n * A brief description of the request body. This could contain examples of use. CommonMark syntax MAY be used for rich text representation.\n */\n description?: string;\n /**\n * The content of the request body. The key is a media type or media type range and the value describes it. For requests that match multiple keys, only the most specific key is applicable. e.g. text/plain overrides text/*\n */\n content: Array<string>;\n /**\n * Determines if the request body is required in the request. Defaults to false.\n */\n required?: boolean;\n }\n\n export type Header = Omit<Parameter, 'name' | 'in'>;\n\n export interface Link {\n /**\n * A relative or absolute reference to an OAS operation. This field is mutually exclusive of the operationId field, and MUST point to an Operation Object. Relative operationRef values MAY be used to locate an existing Operation Object in the OpenAPI definition.\n */\n operationRef?: string;\n /**\n * The name of an existing, resolvable OAS operation, as defined with a unique operationId. This field is mutually exclusive of the operationRef field.\n */\n operationId?: string;\n /**\n * A map representing parameters to pass to an operation as specified with operationId or identified via operationRef. The key is the parameter name to be used, whereas the value can be a constant or an expression to be evaluated and passed to the linked operation. The parameter name can be qualified using the parameter location [{in}.]{name} for operations that use the same parameter name in different locations (e.g. path.id).\n */\n parameters?: Record<string, any>;\n /**\n * A literal value or {expression} to use as a request body when calling the target operation.\n */\n requestBody?: any;\n /**\n * A description of the link. CommonMark syntax MAY be used for rich text representation.\n */\n description?: string;\n }\n\n interface Response {\n /**\n * A short description of the response. CommonMark syntax MAY be used for rich text representation.\n */\n description: string;\n headers?: {\n [header: string]: Header | Reference;\n };\n links?: {\n [link: string]: Link | Reference;\n };\n }\n\n interface Responses {\n default: Response | Reference;\n [httpStatusCode: number]: Response | Reference;\n }\n\n export interface Operation {\n /**\n * A list of tags for API documentation control.\n * Tags can be used for logical grouping of operations by resources or any other qualifier.\n */\n tags?: string[];\n /**\n * A short summary of what the operation does.\n */\n summary?: string;\n /**\n * A verbose explanation of the operation behavior. CommonMark syntax MAY be used for rich text representation.\n */\n description?: string;\n /**\n * Additional external documentation for this operation.\n */\n externalDocs?: {\n /**\n * The URL for the target documentation. Value MUST be in the format of a URL.\n */\n url: string;\n /**\n * A short description of the target documentation. CommonMark syntax MAY be used for rich text representation.\n */\n description?: string;\n };\n\n /**\n * Unique string used to identify the operation.\n * The id MUST be unique among all operations described in the API.\n * The operationId value is case-sensitive.\n * Tools and libraries MAY use the operationId to uniquely identify an operation,\n * therefore, it is RECOMMENDED to follow common programming naming conventions.\n */\n operationId?: string;\n /**\n * A list of parameters that are applicable for this operation.\n * If a parameter is already defined at the Path Item, the new definition will override it but can never remove it.\n * The list MUST NOT include duplicated parameters.\n * A unique parameter is defined by a combination of a name and location.\n * The list can use the Reference Object to link to parameters that are defined at the OpenAPI Object's components/parameters.\n */\n parameters?: Array<Parameter | Reference>;\n /**\n * The request body applicable for this operation. The requestBody is only supported in HTTP methods where the HTTP 1.1 specification RFC7231 has explicitly defined semantics for request bodies. In other cases where the HTTP spec is vague, requestBody SHALL be ignored by consumers.\n */\n requestBody?: RequestBody | Reference;\n /**\n * The list of possible responses as they are returned from executing this operation.\n */\n responses?: Responses;\n /**\n * Declares this operation to be deprecated. Consumers SHOULD refrain from usage of the declared operation. Default value is false.\n */\n deprecated?: boolean;\n }\n\n export interface PathItem {\n /**\n * Allows for an external definition of this path item.\n * The referenced structure MUST be in the format of a Path Item Object.\n * If there are conflicts between the referenced definition and this Path Item's definition, the behavior is undefined.\n */\n $ref?: string;\n /**\n * An optional, string summary, intended to apply to all operations in this path.\n */\n summary?: string;\n /**\n * An optional, string description, intended to apply to all operations in this path.\n * CommonMark syntax MAY be used for rich text representation.\n */\n description?: string;\n /**\n * A definition of a GET operation on this path.\n */\n get?: Operation;\n /**\n * A definition of a PUT operation on this path.\n */\n put?: Operation;\n /**\n * A definition of a POST operation on this path.\n */\n post?: Operation;\n /**\n * A definition of a DELETE operation on this path.\n */\n delete?: Operation;\n /**\n * A definition of a OPTIONS operation on this path.\n */\n options?: Operation;\n /**\n * A definition of a HEAD operation on this path.\n */\n head?: Operation;\n /**\n * A definition of a PATCH operation on this path.\n */\n patch?: Operation;\n /**\n * A definition of a TRACE operation on this path.\n */\n trace?: Operation;\n /**\n * A list of parameters that are applicable for all the operations described under this path. These parameters can be overridden at the operation level, but cannot be removed there. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a name and location. The list can use the Reference Object to link to parameters that are defined at the OpenAPI Object's components/parameters.\n */\n parameters?: Array<Parameter | Reference>;\n }\n\n export interface XML {\n /**\n * \tReplaces the name of the element/attribute used for the described schema property. When defined within items, it will affect the name of the individual XML elements within the list. When defined alongside type being array (outside the items), it will affect the wrapping element and only if wrapped is true. If wrapped is false, it will be ignored.\n */\n name?: string;\n /**\n * The URI of the namespace definition. Value MUST be in the form of an absolute URI.\n */\n namespace?: string;\n /**\n * The prefix to be used for the name.\n */\n prefix?: string;\n /**\n * Declares whether the property definition translates to an attribute instead of an element. Default value is false.\n */\n attribute?: boolean;\n /**\n * MAY be used only for an array definition. Signifies whether the array is wrapped (for example, <books><book/><book/></books>) or unwrapped (<book/><book/>). Default value is false. The definition takes effect only when defined alongside type being array (outside the items).\n */\n wrapped?: boolean;\n }\n\n export interface Schema {\n /**\n * Allows sending a null value for the defined schema. Default value is false.\n */\n nullable?: boolean;\n /**\n * Relevant only for Schema \"properties\" definitions. Declares the property as \"read only\". This means that it MAY be sent as part of a response but SHOULD NOT be sent as part of the request. If the property is marked as readOnly being true and is in the required list, the required will take effect on the response only. A property MUST NOT be marked as both readOnly and writeOnly being true. Default value is false.\n */\n readOnly?: boolean;\n /**\n * Relevant only for Schema \"properties\" definitions. Declares the property as \"write only\". Therefore, it MAY be sent as part of a request but SHOULD NOT be sent as part of the response. If the property is marked as writeOnly being true and is in the required list, the required will take effect on the request only. A property MUST NOT be marked as both readOnly and writeOnly being true. Default value is false.\n */\n writeOnly?: boolean;\n /**\n * This MAY be used only on properties schemas. It has no effect on root schemas. Adds additional metadata to describe the XML representation of this property.\n */\n xml?: XML;\n /**\n * Specifies that a schema is deprecated and SHOULD be transitioned out of usage. Default value is false.\n */\n deprecated?: boolean;\n }\n\n export interface Components {\n /**\n * An object to hold reusable Schema Objects.\n */\n schemas?: Record<string, Schema | Reference>;\n }\n\n export interface OpenAPI {\n /**\n * This string MUST be the semantic version number of the OpenAPI Specification version that the OpenAPI document uses.\n * The openapi field SHOULD be used by tooling specifications and clients to interpret the OpenAPI document.\n * This is not related to the API info.version string.\n */\n openapi: string;\n /**\n * Provides metadata about the API. The metadata MAY be used by tooling as required.\n */\n info: Info;\n /**\n * The available paths and operations for the API.\n */\n paths: {\n [path: string]: PathItem;\n };\n /**\n * An element to hold various schemas for the specification.\n */\n components?: Components;\n }\n}\n"]}
@@ -1,112 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const ast_1 = require("../ast");
4
- const utils_1 = require("./utils");
5
- const types_1 = require("./types");
6
- const titleCase = require("title-case");
7
- function buildPathFromOperation({ url, schema, operation, useRequestBody, }) {
8
- const info = ast_1.getOperationInfo(operation);
9
- const description = resolveDescription(schema, info.operation);
10
- return Object.assign(Object.assign({ operationId: info.name }, (useRequestBody
11
- ? {
12
- requestBody: {
13
- content: {
14
- 'application/json': {
15
- schema: resolveRequestBody(info.operation.variableDefinitions),
16
- },
17
- },
18
- },
19
- }
20
- : {
21
- parameters: resolveParameters(url, info.operation.variableDefinitions),
22
- })), { responses: {
23
- 200: {
24
- description,
25
- content: {
26
- 'application/json': {
27
- schema: resolveResponse({
28
- schema,
29
- operation: info.operation,
30
- }),
31
- },
32
- },
33
- },
34
- } });
35
- }
36
- exports.buildPathFromOperation = buildPathFromOperation;
37
- function resolveParameters(url, variables) {
38
- if (!variables) {
39
- return [];
40
- }
41
- return variables.map((variable) => {
42
- return {
43
- in: isInPath(url, variable.variable.name.value) ? 'path' : 'query',
44
- name: variable.variable.name.value,
45
- required: variable.type.kind === 'NonNullType',
46
- schema: resolveParamSchema(variable.type),
47
- };
48
- });
49
- }
50
- function resolveRequestBody(variables) {
51
- if (!variables) {
52
- return {};
53
- }
54
- const properties = {};
55
- const required = [];
56
- variables.forEach(variable => {
57
- if (variable.type.kind === 'NonNullType') {
58
- required.push(variable.variable.name.value);
59
- }
60
- properties[variable.variable.name.value] = resolveParamSchema(variable.type);
61
- });
62
- return Object.assign({ type: 'object', properties }, (required.length ? { required } : {}));
63
- }
64
- // array -> [type]
65
- // type -> $ref
66
- // scalar -> swagger primitive
67
- function resolveParamSchema(type) {
68
- if (type.kind === 'NonNullType') {
69
- return resolveParamSchema(type.type);
70
- }
71
- if (type.kind === 'ListType') {
72
- return {
73
- type: 'array',
74
- items: resolveParamSchema(type.type),
75
- };
76
- }
77
- const primitive = utils_1.mapToPrimitive(type.name.value);
78
- return (primitive || {
79
- $ref: utils_1.mapToRef(type.name.value),
80
- });
81
- }
82
- function resolveResponse({ schema, operation, }) {
83
- const operationType = operation.operation;
84
- const rootField = operation.selectionSet.selections[0];
85
- if (rootField.kind === 'Field') {
86
- if (operationType === 'query') {
87
- const queryType = schema.getQueryType();
88
- const field = queryType.getFields()[rootField.name.value];
89
- return types_1.resolveFieldType(field.type);
90
- }
91
- if (operationType === 'mutation') {
92
- const mutationType = schema.getMutationType();
93
- const field = mutationType.getFields()[rootField.name.value];
94
- return types_1.resolveFieldType(field.type);
95
- }
96
- }
97
- }
98
- function isInPath(url, param) {
99
- return url.indexOf(`{${param}}`) !== -1;
100
- }
101
- function resolveDescription(schema, operation) {
102
- const selection = operation.selectionSet.selections[0];
103
- const fieldName = selection.name.value;
104
- const typeDefinition = schema.getType(titleCase(operation.operation));
105
- const definitionNode = typeDefinition.astNode;
106
- const fieldNode = definitionNode.fields.find(field => field.name.value === fieldName);
107
- const descriptionDefinition = fieldNode.description;
108
- return descriptionDefinition && descriptionDefinition.value
109
- ? descriptionDefinition.value
110
- : '';
111
- }
112
- //# sourceMappingURL=operations.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"operations.js","sourceRoot":"","sources":["../../src/open-api/operations.ts"],"names":[],"mappings":";;AAUA,gCAA0C;AAC1C,mCAAmD;AACnD,mCAA2C;AAC3C,wCAAyC;AAEzC,SAAgB,sBAAsB,CAAC,EACrC,GAAG,EACH,MAAM,EACN,SAAS,EACT,cAAc,GAMf;IACC,MAAM,IAAI,GAAG,sBAAgB,CAAC,SAAS,CAAE,CAAC;IAE1C,MAAM,WAAW,GAAG,kBAAkB,CAAC,MAAM,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC;IAE/D,qCACE,WAAW,EAAE,IAAI,CAAC,IAAI,IACnB,CAAC,cAAc;QAChB,CAAC,CAAC;YACE,WAAW,EAAE;gBACX,OAAO,EAAE;oBACP,kBAAkB,EAAE;wBAClB,MAAM,EAAE,kBAAkB,CAAC,IAAI,CAAC,SAAS,CAAC,mBAAmB,CAAC;qBAC/D;iBACF;aACF;SACF;QACH,CAAC,CAAC;YACE,UAAU,EAAE,iBAAiB,CAC3B,GAAG,EACH,IAAI,CAAC,SAAS,CAAC,mBAAmB,CACnC;SACF,CAAC,KACN,SAAS,EAAE;YACT,GAAG,EAAE;gBACH,WAAW;gBACX,OAAO,EAAE;oBACP,kBAAkB,EAAE;wBAClB,MAAM,EAAE,eAAe,CAAC;4BACtB,MAAM;4BACN,SAAS,EAAE,IAAI,CAAC,SAAS;yBAC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IAAI,CAAC,KAAK,CAAC,CAAC;YAE7D,OAAO,wBAAgB,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;SACrC;KACF;AACH,CAAC;AAED,SAAS,QAAQ,CAAC,GAAW,EAAE,KAAa;IAC1C,OAAO,GAAG,CAAC,OAAO,CAAC,IAAI,KAAK,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC;AAC1C,CAAC;AAED,SAAS,kBAAkB,CACzB,MAAqB,EACrB,SAAkC;IAElC,MAAM,SAAS,GAAG,SAAS,CAAC,YAAY,CAAC,UAAU,CAAC,CAAC,CAAc,CAAC;IACpE,MAAM,SAAS,GAAG,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC;IACvC,MAAM,cAAc,GAAG,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,CAAC;IACtE,MAAM,cAAc,GAAG,cAAe,CAAC,OAAmC,CAAC;IAC3E,MAAM,SAAS,GAAG,cAAc,CAAC,MAAO,CAAC,IAAI,CAC3C,KAAK,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,KAAK,SAAS,CACxC,CAAC;IACF,MAAM,qBAAqB,GAAG,SAAU,CAAC,WAAW,CAAC;IACrD,OAAO,qBAAqB,IAAI,qBAAqB,CAAC,KAAK;QACzD,CAAC,CAAC,qBAAqB,CAAC,KAAK;QAC7B,CAAC,CAAC,EAAE,CAAC;AACT,CAAC","sourcesContent":["import {\n DocumentNode,\n GraphQLSchema,\n VariableDefinitionNode,\n TypeNode,\n OperationDefinitionNode,\n ObjectTypeDefinitionNode,\n FieldNode,\n} from 'graphql';\n\nimport { getOperationInfo } from '../ast';\nimport { mapToPrimitive, mapToRef } from './utils';\nimport { resolveFieldType } from './types';\nimport titleCase = require('title-case');\n\nexport function buildPathFromOperation({\n url,\n schema,\n operation,\n useRequestBody,\n}: {\n url: string;\n schema: GraphQLSchema;\n operation: DocumentNode;\n useRequestBody: boolean;\n}): any {\n const info = getOperationInfo(operation)!;\n\n const description = resolveDescription(schema, info.operation);\n\n return {\n operationId: info.name,\n ...(useRequestBody\n ? {\n requestBody: {\n content: {\n 'application/json': {\n schema: resolveRequestBody(info.operation.variableDefinitions),\n },\n },\n },\n }\n : {\n parameters: resolveParameters(\n url,\n info.operation.variableDefinitions\n ),\n }),\n responses: {\n 200: {\n description,\n content: {\n 'application/json': {\n schema: resolveResponse({\n schema,\n operation: info.operation,\n }),\n },\n },\n },\n },\n };\n}\n\nfunction resolveParameters(\n url: string,\n variables: ReadonlyArray<VariableDefinitionNode> | undefined\n) {\n if (!variables) {\n return [];\n }\n\n return variables.map((variable: any) => {\n return {\n in: isInPath(url, variable.variable.name.value) ? 'path' : 'query',\n name: variable.variable.name.value,\n required: variable.type.kind === 'NonNullType',\n schema: resolveParamSchema(variable.type),\n };\n });\n}\n\nfunction resolveRequestBody(\n variables: ReadonlyArray<VariableDefinitionNode> | undefined\n) {\n if (!variables) {\n return {};\n }\n\n const properties: Record<string, any> = {};\n const required: string[] = [];\n\n variables.forEach(variable => {\n if (variable.type.kind === 'NonNullType') {\n required.push(variable.variable.name.value);\n }\n\n properties[variable.variable.name.value] = resolveParamSchema(\n variable.type\n );\n });\n\n return {\n type: 'object',\n properties,\n ...(required.length ? { required } : {}),\n };\n}\n\n// array -> [type]\n// type -> $ref\n// scalar -> swagger primitive\nfunction resolveParamSchema(type: TypeNode): any {\n if (type.kind === 'NonNullType') {\n return resolveParamSchema(type.type);\n }\n\n if (type.kind === 'ListType') {\n return {\n type: 'array',\n items: resolveParamSchema(type.type),\n };\n }\n\n const primitive = mapToPrimitive(type.name.value);\n\n return (\n primitive || {\n $ref: mapToRef(type.name.value),\n }\n );\n}\n\nfunction resolveResponse({\n schema,\n operation,\n}: {\n schema: GraphQLSchema;\n operation: OperationDefinitionNode;\n}) {\n const operationType = operation.operation;\n const rootField = operation.selectionSet.selections[0];\n\n if (rootField.kind === 'Field') {\n if (operationType === 'query') {\n const queryType = schema.getQueryType()!;\n const field = queryType.getFields()[rootField.name.value];\n\n return resolveFieldType(field.type);\n }\n\n if (operationType === 'mutation') {\n const mutationType = schema.getMutationType()!;\n const field = mutationType.getFields()[rootField.name.value];\n\n return resolveFieldType(field.type);\n }\n }\n}\n\nfunction isInPath(url: string, param: string): boolean {\n return url.indexOf(`{${param}}`) !== -1;\n}\n\nfunction resolveDescription(\n schema: GraphQLSchema,\n operation: OperationDefinitionNode\n) {\n const selection = operation.selectionSet.selections[0] as FieldNode;\n const fieldName = selection.name.value;\n const typeDefinition = schema.getType(titleCase(operation.operation));\n const definitionNode = typeDefinition!.astNode as ObjectTypeDefinitionNode;\n const fieldNode = definitionNode.fields!.find(\n field => field.name.value === fieldName\n );\n const descriptionDefinition = fieldNode!.description;\n return descriptionDefinition && descriptionDefinition.value\n ? descriptionDefinition.value\n : '';\n}\n"]}
@@ -1,50 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const graphql_1 = require("graphql");
4
- const utils_1 = require("./utils");
5
- function buildSchemaObjectFromType(type) {
6
- const required = [];
7
- const properties = {};
8
- const fields = type.getFields();
9
- for (const fieldName in fields) {
10
- const field = fields[fieldName];
11
- if (graphql_1.isNonNullType(field.type)) {
12
- required.push(field.name);
13
- }
14
- properties[fieldName] = resolveField(field);
15
- }
16
- return Object.assign(Object.assign({ type: 'object' }, (required.length ? { required } : {})), { properties });
17
- }
18
- exports.buildSchemaObjectFromType = buildSchemaObjectFromType;
19
- function resolveField(field) {
20
- return resolveFieldType(field.type);
21
- }
22
- // array -> [type]
23
- // type -> $ref
24
- // scalar -> swagger primitive
25
- function resolveFieldType(type) {
26
- if (graphql_1.isNonNullType(type)) {
27
- return resolveFieldType(type.ofType);
28
- }
29
- if (graphql_1.isListType(type)) {
30
- return {
31
- type: 'array',
32
- items: resolveFieldType(type.ofType),
33
- };
34
- }
35
- if (graphql_1.isObjectType(type)) {
36
- return {
37
- $ref: utils_1.mapToRef(type.name),
38
- };
39
- }
40
- if (graphql_1.isScalarType(type)) {
41
- return (utils_1.mapToPrimitive(type.name) || {
42
- type: 'object',
43
- });
44
- }
45
- return {
46
- type: 'object',
47
- };
48
- }
49
- exports.resolveFieldType = resolveFieldType;
50
- //# sourceMappingURL=types.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/open-api/types.ts"],"names":[],"mappings":";;AAAA,qCAWiB;AACjB,mCAAmD;AAEnD,SAAgB,yBAAyB,CACvC,IAAgD;IAEhD,MAAM,QAAQ,GAAa,EAAE,CAAC;IAC9B,MAAM,UAAU,GAAwB,EAAE,CAAC;IAE3C,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,EAAE,CAAC;IAEhC,KAAK,MAAM,SAAS,IAAI,MAAM,EAAE;QAC9B,MAAM,KAAK,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC;QAEhC,IAAI,uBAAa,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE;YAC7B,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;SAC3B;QAED,UAAU,CAAC,SAAS,CAAC,GAAG,YAAY,CAAC,KAAK,CAAC,CAAC;KAC7C;IAED,qCACE,IAAI,EAAE,QAAQ,IACX,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,KACxC,UAAU,IACV;AACJ,CAAC;AAvBD,8DAuBC;AAED,SAAS,YAAY,CAAC,KAAiD;IACrE,OAAO,gBAAgB,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;AACtC,CAAC;AAED,kBAAkB;AAClB,eAAe;AACf,8BAA8B;AAC9B,SAAgB,gBAAgB,CAC9B,IAA0C;IAE1C,IAAI,uBAAa,CAAC,IAAI,CAAC,EAAE;QACvB,OAAO,gBAAgB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;KACtC;IAED,IAAI,oBAAU,CAAC,IAAI,CAAC,EAAE;QACpB,OAAO;YACL,IAAI,EAAE,OAAO;YACb,KAAK,EAAE,gBAAgB,CAAC,IAAI,CAAC,MAAM,CAAC;SACrC,CAAC;KACH;IAED,IAAI,sBAAY,CAAC,IAAI,CAAC,EAAE;QACtB,OAAO;YACL,IAAI,EAAE,gBAAQ,CAAC,IAAI,CAAC,IAAI,CAAC;SAC1B,CAAC;KACH;IAED,IAAI,sBAAY,CAAC,IAAI,CAAC,EAAE;QACtB,OAAO,CACL,sBAAc,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI;YAC3B,IAAI,EAAE,QAAQ;SACf,CACF,CAAC;KACH;IAED,OAAO;QACL,IAAI,EAAE,QAAQ;KACf,CAAC;AACJ,CAAC;AA/BD,4CA+BC","sourcesContent":["import {\n GraphQLObjectType,\n GraphQLInputObjectType,\n GraphQLField,\n GraphQLInputField,\n isNonNullType,\n GraphQLOutputType,\n isListType,\n isObjectType,\n isScalarType,\n GraphQLNamedType,\n} from 'graphql';\nimport { mapToPrimitive, mapToRef } from './utils';\n\nexport function buildSchemaObjectFromType(\n type: GraphQLObjectType | GraphQLInputObjectType\n): any {\n const required: string[] = [];\n const properties: Record<string, any> = {};\n\n const fields = type.getFields();\n\n for (const fieldName in fields) {\n const field = fields[fieldName];\n\n if (isNonNullType(field.type)) {\n required.push(field.name);\n }\n\n properties[fieldName] = resolveField(field);\n }\n\n return {\n type: 'object',\n ...(required.length ? { required } : {}),\n properties,\n };\n}\n\nfunction resolveField(field: GraphQLField<any, any> | GraphQLInputField) {\n return resolveFieldType(field.type);\n}\n\n// array -> [type]\n// type -> $ref\n// scalar -> swagger primitive\nexport function resolveFieldType(\n type: GraphQLOutputType | GraphQLNamedType\n): any {\n if (isNonNullType(type)) {\n return resolveFieldType(type.ofType);\n }\n\n if (isListType(type)) {\n return {\n type: 'array',\n items: resolveFieldType(type.ofType),\n };\n }\n\n if (isObjectType(type)) {\n return {\n $ref: mapToRef(type.name),\n };\n }\n\n if (isScalarType(type)) {\n return (\n mapToPrimitive(type.name) || {\n type: 'object',\n }\n );\n }\n\n return {\n type: 'object',\n };\n}\n"]}
@@ -1,29 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- function mapToPrimitive(type) {
4
- const formatMap = {
5
- Int: {
6
- type: 'integer',
7
- format: 'int32',
8
- },
9
- Float: {
10
- type: 'number',
11
- format: 'float',
12
- },
13
- String: {
14
- type: 'string',
15
- },
16
- Boolean: {
17
- type: 'boolean',
18
- },
19
- };
20
- if (formatMap[type]) {
21
- return formatMap[type];
22
- }
23
- }
24
- exports.mapToPrimitive = mapToPrimitive;
25
- function mapToRef(type) {
26
- return `#/components/schemas/${type}`;
27
- }
28
- exports.mapToRef = mapToRef;
29
- //# sourceMappingURL=utils.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/open-api/utils.ts"],"names":[],"mappings":";;AAAA,SAAgB,cAAc,CAAC,IAAY;IACzC,MAAM,SAAS,GAAwB;QACrC,GAAG,EAAE;YACH,IAAI,EAAE,SAAS;YACf,MAAM,EAAE,OAAO;SAChB;QACD,KAAK,EAAE;YACL,IAAI,EAAE,QAAQ;YACd,MAAM,EAAE,OAAO;SAChB;QACD,MAAM,EAAE;YACN,IAAI,EAAE,QAAQ;SACf;QACD,OAAO,EAAE;YACP,IAAI,EAAE,SAAS;SAChB;KACF,CAAC;IAEF,IAAI,SAAS,CAAC,IAAI,CAAC,EAAE;QACnB,OAAO,SAAS,CAAC,IAAI,CAAC,CAAC;KACxB;AACH,CAAC;AArBD,wCAqBC;AAED,SAAgB,QAAQ,CAAC,IAAY;IACnC,OAAO,wBAAwB,IAAI,EAAE,CAAC;AACxC,CAAC;AAFD,4BAEC","sourcesContent":["export function mapToPrimitive(type: string) {\n const formatMap: Record<string, any> = {\n Int: {\n type: 'integer',\n format: 'int32',\n },\n Float: {\n type: 'number',\n format: 'float',\n },\n String: {\n type: 'string',\n },\n Boolean: {\n type: 'boolean',\n },\n };\n\n if (formatMap[type]) {\n return formatMap[type];\n }\n}\n\nexport function mapToRef(type: string) {\n return `#/components/schemas/${type}`;\n}\n"]}
package/dist/operation.js DELETED
@@ -1,258 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const graphql_1 = require("graphql");
4
- const changeCase = require("change-case");
5
- const logger_1 = require("./logger");
6
- let operationVariables = [];
7
- function addOperationVariable(variable) {
8
- operationVariables.push(variable);
9
- }
10
- function resetOperationVariables() {
11
- operationVariables = [];
12
- }
13
- function buildOperationName(name) {
14
- return changeCase.camel(name);
15
- }
16
- function buildOperation({ schema, kind, field, models, ignore, depthLimit, }) {
17
- resetOperationVariables();
18
- logger_1.logger.debug(`[Sofa] Building ${field} ${kind}`);
19
- const document = buildDocumentNode({
20
- schema,
21
- fieldName: field,
22
- kind,
23
- models,
24
- ignore,
25
- depthLimit: depthLimit || 1,
26
- });
27
- // attach variables
28
- document.definitions[0].variableDefinitions = [
29
- ...operationVariables,
30
- ];
31
- resetOperationVariables();
32
- return document;
33
- }
34
- exports.buildOperation = buildOperation;
35
- function buildDocumentNode({ schema, fieldName, kind, models, ignore, depthLimit, }) {
36
- const typeMap = {
37
- query: schema.getQueryType(),
38
- mutation: schema.getMutationType(),
39
- subscription: schema.getSubscriptionType(),
40
- };
41
- const type = typeMap[kind];
42
- const field = type.getFields()[fieldName];
43
- const operationName = buildOperationName(`${fieldName}_${kind}`);
44
- if (field.args) {
45
- field.args.forEach(arg => {
46
- addOperationVariable(resolveVariable(arg));
47
- });
48
- }
49
- const operationNode = {
50
- kind: 'OperationDefinition',
51
- operation: kind,
52
- name: {
53
- kind: 'Name',
54
- value: operationName,
55
- },
56
- variableDefinitions: [],
57
- selectionSet: {
58
- kind: 'SelectionSet',
59
- selections: [
60
- resolveField({
61
- type,
62
- field,
63
- models,
64
- firstCall: true,
65
- path: [],
66
- ancestors: [],
67
- ignore,
68
- depthLimit,
69
- }),
70
- ],
71
- },
72
- };
73
- const document = {
74
- kind: 'Document',
75
- definitions: [operationNode],
76
- };
77
- return document;
78
- }
79
- function resolveSelectionSet({ parent, type, models, firstCall, path, ancestors, ignore, depthLimit, }) {
80
- if (graphql_1.isUnionType(type)) {
81
- const types = type.getTypes();
82
- return {
83
- kind: 'SelectionSet',
84
- selections: types
85
- .filter(t => !hasCircularRef([...ancestors, t], {
86
- depth: depthLimit,
87
- }))
88
- .map(t => {
89
- const fields = t.getFields();
90
- return {
91
- kind: 'InlineFragment',
92
- typeCondition: {
93
- kind: 'NamedType',
94
- name: {
95
- kind: 'Name',
96
- value: t.name,
97
- },
98
- },
99
- selectionSet: {
100
- kind: 'SelectionSet',
101
- selections: Object.keys(fields).map(fieldName => {
102
- return resolveField({
103
- type: t,
104
- field: fields[fieldName],
105
- models,
106
- path: [...path, fieldName],
107
- ancestors,
108
- ignore,
109
- depthLimit,
110
- });
111
- }),
112
- },
113
- };
114
- }),
115
- };
116
- }
117
- if (graphql_1.isObjectType(type)) {
118
- const isIgnored = ignore.includes(type.name) ||
119
- ignore.includes(`${parent.name}.${path[path.length - 1]}`);
120
- const isModel = models.includes(type.name);
121
- if (!firstCall && isModel && !isIgnored) {
122
- return {
123
- kind: 'SelectionSet',
124
- selections: [
125
- {
126
- kind: 'Field',
127
- name: {
128
- kind: 'Name',
129
- value: 'id',
130
- },
131
- },
132
- ],
133
- };
134
- }
135
- const fields = type.getFields();
136
- return {
137
- kind: 'SelectionSet',
138
- selections: Object.keys(fields)
139
- .filter(fieldName => {
140
- return !hasCircularRef([...ancestors, graphql_1.getNamedType(fields[fieldName].type)], {
141
- depth: depthLimit,
142
- });
143
- })
144
- .map(fieldName => {
145
- return resolveField({
146
- type: type,
147
- field: fields[fieldName],
148
- models,
149
- path: [...path, fieldName],
150
- ancestors,
151
- ignore,
152
- depthLimit,
153
- });
154
- }),
155
- };
156
- }
157
- }
158
- function resolveVariable(arg, name) {
159
- function resolveVariableType(type) {
160
- if (graphql_1.isListType(type)) {
161
- return {
162
- kind: 'ListType',
163
- type: resolveVariableType(type.ofType),
164
- };
165
- }
166
- if (graphql_1.isNonNullType(type)) {
167
- return {
168
- kind: 'NonNullType',
169
- type: resolveVariableType(type.ofType),
170
- };
171
- }
172
- return {
173
- kind: 'NamedType',
174
- name: {
175
- kind: 'Name',
176
- value: type.name,
177
- },
178
- };
179
- }
180
- return {
181
- kind: 'VariableDefinition',
182
- variable: {
183
- kind: 'Variable',
184
- name: {
185
- kind: 'Name',
186
- value: name || arg.name,
187
- },
188
- },
189
- type: resolveVariableType(arg.type),
190
- };
191
- }
192
- function getArgumentName(name, path) {
193
- return changeCase.camel([...path, name].join('_'));
194
- }
195
- function resolveField({ type, field, models, firstCall, path, ancestors, ignore, depthLimit, }) {
196
- const namedType = graphql_1.getNamedType(field.type);
197
- let args = [];
198
- if (field.args && field.args.length) {
199
- args = field.args.map(arg => {
200
- if (!firstCall) {
201
- addOperationVariable(resolveVariable(arg, getArgumentName(arg.name, path)));
202
- }
203
- return {
204
- kind: 'Argument',
205
- name: {
206
- kind: 'Name',
207
- value: arg.name,
208
- },
209
- value: {
210
- kind: 'Variable',
211
- name: {
212
- kind: 'Name',
213
- value: getArgumentName(arg.name, path),
214
- },
215
- },
216
- };
217
- });
218
- }
219
- if (!graphql_1.isScalarType(namedType)) {
220
- return {
221
- kind: 'Field',
222
- name: {
223
- kind: 'Name',
224
- value: field.name,
225
- },
226
- selectionSet: resolveSelectionSet({
227
- parent: type,
228
- type: namedType,
229
- models,
230
- firstCall,
231
- path: [...path, field.name],
232
- ancestors: [...ancestors, type],
233
- ignore,
234
- depthLimit,
235
- }),
236
- arguments: args,
237
- };
238
- }
239
- return {
240
- kind: 'Field',
241
- name: {
242
- kind: 'Name',
243
- value: field.name,
244
- },
245
- arguments: args,
246
- };
247
- }
248
- function hasCircularRef(types, config = {
249
- depth: 1,
250
- }) {
251
- const type = types[types.length - 1];
252
- if (graphql_1.isScalarType(type)) {
253
- return false;
254
- }
255
- const size = types.filter(t => t.name === type.name).length;
256
- return size > config.depth;
257
- }
258
- //# sourceMappingURL=operation.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"operation.js","sourceRoot":"","sources":["../src/operation.ts"],"names":[],"mappings":";;AAAA,qCA0BiB;AACjB,0CAA0C;AAG1C,qCAAkC;AAElC,IAAI,kBAAkB,GAA6B,EAAE,CAAC;AAEtD,SAAS,oBAAoB,CAAC,QAAgC;IAC5D,kBAAkB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;AACpC,CAAC;AAED,SAAS,uBAAuB;IAC9B,kBAAkB,GAAG,EAAE,CAAC;AAC1B,CAAC;AAED,SAAS,kBAAkB,CAAC,IAAY;IACtC,OAAO,UAAU,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;AAChC,CAAC;AAKD,SAAgB,cAAc,CAAC,EAC7B,MAAM,EACN,IAAI,EACJ,KAAK,EACL,MAAM,EACN,MAAM,EACN,UAAU,GAQX;IACC,uBAAuB,EAAE,CAAC;IAE1B,eAAM,CAAC,KAAK,CAAC,mBAAmB,KAAK,IAAI,IAAI,EAAE,CAAC,CAAC;IAEjD,MAAM,QAAQ,GAAG,iBAAiB,CAAC;QACjC,MAAM;QACN,SAAS,EAAE,KAAK;QAChB,IAAI;QACJ,MAAM;QACN,MAAM;QACN,UAAU,EAAE,UAAU,IAAI,CAAC;KAC5B,CAAC,CAAC;IAEH,mBAAmB;IAClB,QAAQ,CAAC,WAAW,CAAC,CAAC,CAAS,CAAC,mBAAmB,GAAG;QACrD,GAAG,kBAAkB;KACtB,CAAC;IAEF,uBAAuB,EAAE,CAAC;IAE1B,OAAO,QAAQ,CAAC;AAClB,CAAC;AApCD,wCAoCC;AAED,SAAS,iBAAiB,CAAC,EACzB,MAAM,EACN,SAAS,EACT,IAAI,EACJ,MAAM,EACN,MAAM,EACN,UAAU,GAQX;IACC,MAAM,OAAO,GAAiD;QAC5D,KAAK,EAAE,MAAM,CAAC,YAAY,EAAG;QAC7B,QAAQ,EAAE,MAAM,CA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,CAAC;IAC5D,OAAO,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC;AAC7B,CAAC","sourcesContent":["import {\n GraphQLSchema,\n GraphQLObjectType,\n isObjectType,\n getNamedType,\n isUnionType,\n DocumentNode,\n OperationDefinitionNode,\n VariableDefinitionNode,\n isNonNullType,\n SelectionNode,\n InlineFragmentNode,\n GraphQLNamedType,\n SelectionSetNode,\n isScalarType,\n TypeNode,\n isListType,\n ArgumentNode,\n GraphQLField,\n GraphQLArgument,\n GraphQLInputType,\n GraphQLList,\n ListTypeNode,\n GraphQLNonNull,\n NonNullTypeNode,\n OperationTypeNode,\n} from 'graphql';\nimport * as changeCase from 'change-case';\n\nimport { Ignore } from './types';\nimport { logger } from './logger';\n\nlet operationVariables: VariableDefinitionNode[] = [];\n\nfunction addOperationVariable(variable: VariableDefinitionNode) {\n operationVariables.push(variable);\n}\n\nfunction resetOperationVariables() {\n operationVariables = [];\n}\n\nfunction buildOperationName(name: string) {\n return changeCase.camel(name);\n}\n\nexport type Skip = string[];\nexport type Force = string[];\n\nexport function buildOperation({\n schema,\n kind,\n field,\n models,\n ignore,\n depthLimit,\n}: {\n schema: GraphQLSchema;\n kind: OperationTypeNode;\n field: string;\n models: string[];\n ignore: Ignore;\n depthLimit?: number;\n}) {\n resetOperationVariables();\n\n logger.debug(`[Sofa] Building ${field} ${kind}`);\n\n const document = buildDocumentNode({\n schema,\n fieldName: field,\n kind,\n models,\n ignore,\n depthLimit: depthLimit || 1,\n });\n\n // attach variables\n (document.definitions[0] as any).variableDefinitions = [\n ...operationVariables,\n ];\n\n resetOperationVariables();\n\n return document;\n}\n\nfunction buildDocumentNode({\n schema,\n fieldName,\n kind,\n models,\n ignore,\n depthLimit,\n}: {\n schema: GraphQLSchema;\n fieldName: string;\n kind: OperationTypeNode;\n models: string[];\n ignore: Ignore;\n depthLimit: number;\n}) {\n const typeMap: Record<OperationTypeNode, GraphQLObjectType> = {\n query: schema.getQueryType()!,\n mutation: schema.getMutationType()!,\n subscription: schema.getSubscriptionType()!,\n };\n const type = typeMap[kind];\n const field = type.getFields()[fieldName];\n const operationName = buildOperationName(`${fieldName}_${kind}`);\n\n if (field.args) {\n field.args.forEach(arg => {\n addOperationVariable(resolveVariable(arg));\n });\n }\n\n const operationNode: OperationDefinitionNode = {\n kind: 'OperationDefinition',\n operation: kind,\n name: {\n kind: 'Name',\n value: operationName,\n },\n variableDefinitions: [],\n selectionSet: {\n kind: 'SelectionSet',\n selections: [\n resolveField({\n type,\n field,\n models,\n firstCall: true,\n path: [],\n ancestors: [],\n ignore,\n depthLimit,\n }),\n ],\n },\n };\n const document: DocumentNode = {\n kind: 'Document',\n definitions: [operationNode],\n };\n\n return document;\n}\n\nfunction resolveSelectionSet({\n parent,\n type,\n models,\n firstCall,\n path,\n ancestors,\n ignore,\n depthLimit,\n}: {\n parent: GraphQLNamedType;\n type: GraphQLNamedType;\n models: string[];\n path: string[];\n ancestors: GraphQLNamedType[];\n firstCall?: boolean;\n ignore: Ignore;\n depthLimit: number;\n}): SelectionSetNode | undefined {\n if (isUnionType(type)) {\n const types = type.getTypes();\n\n return {\n kind: 'SelectionSet',\n selections: types\n .filter(\n t =>\n !hasCircularRef([...ancestors, t], {\n depth: depthLimit,\n })\n )\n .map<InlineFragmentNode>(t => {\n const fields = t.getFields();\n\n return {\n kind: 'InlineFragment',\n typeCondition: {\n kind: 'NamedType',\n name: {\n kind: 'Name',\n value: t.name,\n },\n },\n selectionSet: {\n kind: 'SelectionSet',\n selections: Object.keys(fields).map(fieldName => {\n return resolveField({\n type: t,\n field: fields[fieldName],\n models,\n path: [...path, fieldName],\n ancestors,\n ignore,\n depthLimit,\n });\n }),\n },\n };\n }),\n };\n }\n\n if (isObjectType(type)) {\n const isIgnored =\n ignore.includes(type.name) ||\n ignore.includes(`${parent.name}.${path[path.length - 1]}`);\n const isModel = models.includes(type.name);\n\n if (!firstCall && isModel && !isIgnored) {\n return {\n kind: 'SelectionSet',\n selections: [\n {\n kind: 'Field',\n name: {\n kind: 'Name',\n value: 'id',\n },\n },\n ],\n };\n }\n\n const fields = type.getFields();\n\n return {\n kind: 'SelectionSet',\n selections: Object.keys(fields)\n .filter(fieldName => {\n return !hasCircularRef(\n [...ancestors, getNamedType(fields[fieldName].type)],\n {\n depth: depthLimit,\n }\n );\n })\n .map(fieldName => {\n return resolveField({\n type: type,\n field: fields[fieldName],\n models,\n path: [...path, fieldName],\n ancestors,\n ignore,\n depthLimit,\n });\n }),\n };\n }\n}\n\nfunction resolveVariable(\n arg: GraphQLArgument,\n name?: string\n): VariableDefinitionNode {\n function resolveVariableType(type: GraphQLList<any>): ListTypeNode;\n function resolveVariableType(type: GraphQLNonNull<any>): NonNullTypeNode;\n function resolveVariableType(type: GraphQLInputType): TypeNode;\n function resolveVariableType(type: GraphQLInputType): TypeNode {\n if (isListType(type)) {\n return {\n kind: 'ListType',\n type: resolveVariableType(type.ofType),\n };\n }\n\n if (isNonNullType(type)) {\n return {\n kind: 'NonNullType',\n type: resolveVariableType(type.ofType),\n };\n }\n\n return {\n kind: 'NamedType',\n name: {\n kind: 'Name',\n value: type.name,\n },\n };\n }\n\n return {\n kind: 'VariableDefinition',\n variable: {\n kind: 'Variable',\n name: {\n kind: 'Name',\n value: name || arg.name,\n },\n },\n type: resolveVariableType(arg.type),\n };\n}\n\nfunction getArgumentName(name: string, path: string[]): string {\n return changeCase.camel([...path, name].join('_'));\n}\n\nfunction resolveField({\n type,\n field,\n models,\n firstCall,\n path,\n ancestors,\n ignore,\n depthLimit,\n}: {\n type: GraphQLObjectType;\n field: GraphQLField<any, any>;\n models: string[];\n path: string[];\n ancestors: GraphQLNamedType[];\n firstCall?: boolean;\n ignore: Ignore;\n depthLimit: number;\n}): SelectionNode {\n const namedType = getNamedType(field.type);\n let args: ArgumentNode[] = [];\n\n if (field.args && field.args.length) {\n args = field.args.map<ArgumentNode>(arg => {\n if (!firstCall) {\n addOperationVariable(\n resolveVariable(arg, getArgumentName(arg.name, path))\n );\n }\n\n return {\n kind: 'Argument',\n name: {\n kind: 'Name',\n value: arg.name,\n },\n value: {\n kind: 'Variable',\n name: {\n kind: 'Name',\n value: getArgumentName(arg.name, path),\n },\n },\n };\n });\n }\n\n if (!isScalarType(namedType)) {\n return {\n kind: 'Field',\n name: {\n kind: 'Name',\n value: field.name,\n },\n selectionSet: resolveSelectionSet({\n parent: type,\n type: namedType,\n models,\n firstCall,\n path: [...path, field.name],\n ancestors: [...ancestors, type],\n ignore,\n depthLimit,\n }),\n arguments: args,\n };\n }\n\n return {\n kind: 'Field',\n name: {\n kind: 'Name',\n value: field.name,\n },\n arguments: args,\n };\n}\n\nfunction hasCircularRef(\n types: GraphQLNamedType[],\n config: {\n depth: number;\n } = {\n depth: 1,\n }\n): boolean {\n const type = types[types.length - 1];\n\n if (isScalarType(type)) {\n return false;\n }\n\n const size = types.filter(t => t.name === type.name).length;\n return size > config.depth;\n}\n"]}
package/dist/parse.js DELETED
@@ -1,46 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const graphql_1 = require("graphql");
4
- function parseVariable({ value, variable, schema, }) {
5
- if (!value) {
6
- return;
7
- }
8
- return resolveVariable({
9
- value,
10
- type: variable.type,
11
- schema,
12
- });
13
- }
14
- exports.parseVariable = parseVariable;
15
- function resolveVariable({ value, type, schema, }) {
16
- if (type.kind === 'NamedType') {
17
- const namedType = schema.getType(type.name.value);
18
- if (graphql_1.isScalarType(namedType)) {
19
- // GraphQLBoolean.serialize expects a boolean or a number only
20
- if (graphql_1.isEqualType(graphql_1.GraphQLBoolean, namedType)) {
21
- // we don't support TRUE
22
- value = value === 'true';
23
- }
24
- return namedType.serialize(value);
25
- }
26
- if (graphql_1.isInputObjectType(namedType)) {
27
- return value && typeof value === 'object' ? value : JSON.parse(value);
28
- }
29
- return value;
30
- }
31
- if (type.kind === 'ListType') {
32
- return value.map(val => resolveVariable({
33
- value: val,
34
- type: type.type,
35
- schema,
36
- }));
37
- }
38
- if (type.kind === 'NonNullType') {
39
- return resolveVariable({
40
- value: value,
41
- type: type.type,
42
- schema,
43
- });
44
- }
45
- }
46
- //# sourceMappingURL=parse.js.map
package/dist/parse.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"parse.js","sourceRoot":"","sources":["../src/parse.ts"],"names":[],"mappings":";;AAAA,qCAQiB;AAEjB,SAAgB,aAAa,CAAC,EAC5B,KAAK,EACL,QAAQ,EACR,MAAM,GAKP;IACC,IAAI,CAAC,KAAK,EAAE;QACV,OAAO;KACR;IAED,OAAO,eAAe,CAAC;QACrB,KAAK;QACL,IAAI,EAAE,QAAQ,CAAC,IAAI;QACnB,MAAM;KACP,CAAC,CAAC;AACL,CAAC;AAlBD,sCAkBC;AAED,SAAS,eAAe,CAAC,EACvB,KAAK,EACL,IAAI,EACJ,MAAM,GAKP;IACC,IAAI,IAAI,CAAC,IAAI,KAAK,WAAW,EAAE;QAC7B,MAAM,SAAS,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAElD,IAAI,sBAAY,CAAC,SAAS,CAAC,EAAE;YAC3B,8DAA8D;YAC9D,IAAI,qBAAW,CAAC,wBAAc,EAAE,SAAS,CAAC,EAAE;gBAC1C,wBAAwB;gBACxB,KAAK,GAAG,KAAK,KAAK,MAAM,CAAC;aAC1B;YAED,OAAO,SAAS,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;SACnC;QAED,IAAI,2BAAiB,CAAC,SAAS,CAAC,EAAE;YAChC,OAAO,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;SACvE;QAED,OAAO,KAAK,CAAC;KACd;IAED,IAAI,IAAI,CAAC,IAAI,KAAK,UAAU,EAAE;QAC5B,OAAQ,KAAe,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAChC,eAAe,CAAC;YACd,KAAK,EAAE,GAAG;YACV,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,MAAM;SACP,CAAC,CACH,CAAC;KACH;IAED,IAAI,IAAI,CAAC,IAAI,KAAK,aAAa,EAAE;QAC/B,OAAO,eAAe,CAAC;YACrB,KAAK,EAAE,KAAK;YACZ,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,MAAM;SACP,CAAC,CAAC;KACJ;AACH,CAAC","sourcesContent":["import {\n VariableDefinitionNode,\n GraphQLSchema,\n TypeNode,\n isScalarType,\n isEqualType,\n GraphQLBoolean,\n isInputObjectType,\n} from 'graphql';\n\nexport function parseVariable({\n value,\n variable,\n schema,\n}: {\n value: any;\n variable: VariableDefinitionNode;\n schema: GraphQLSchema;\n}) {\n if (!value) {\n return;\n }\n\n return resolveVariable({\n value,\n type: variable.type,\n schema,\n });\n}\n\nfunction resolveVariable({\n value,\n type,\n schema,\n}: {\n value: any;\n type: TypeNode;\n schema: GraphQLSchema;\n}): any | any[] {\n if (type.kind === 'NamedType') {\n const namedType = schema.getType(type.name.value);\n\n if (isScalarType(namedType)) {\n // GraphQLBoolean.serialize expects a boolean or a number only\n if (isEqualType(GraphQLBoolean, namedType)) {\n // we don't support TRUE\n value = value === 'true';\n }\n\n return namedType.serialize(value);\n }\n\n if (isInputObjectType(namedType)) {\n return value && typeof value === 'object' ? value : JSON.parse(value);\n }\n\n return value;\n }\n\n if (type.kind === 'ListType') {\n return (value as any[]).map(val =>\n resolveVariable({\n value: val,\n type: type.type,\n schema,\n })\n );\n }\n\n if (type.kind === 'NonNullType') {\n return resolveVariable({\n value: value,\n type: type.type,\n schema,\n });\n }\n}\n"]}