chore: Move graphl to a single place (#9303)

* chore: Move graphl to a single place

* add new line
This commit is contained in:
Adrien de Peretti authored and GitHub committed 2024-09-25 12:04:25 +02:00
1 parent 1d3a60023a
commit 358435d715
30 files changed
+73 -57

No files matched your search

+2
View File
@@ -24,3 +24,5 @@ build/**
**/stats **/stats
.favorites.json .favorites.json
.vscode .vscode
**/tsconfig.tsbuildinfo
+2 -1
View File
@@ -19,7 +19,8 @@
"strictFunctionTypes": true, "strictFunctionTypes": true,
"noImplicitThis": true, "noImplicitThis": true,
"allowJs": true, "allowJs": true,
"skipLibCheck": true "skipLibCheck": true,
"rootDir": "${configDir}/src"
}, },
"include": ["${configDir}/src"], "include": ["${configDir}/src"],
"exclude": ["${configDir}/dist", "${configDir}/node_modules"] "exclude": ["${configDir}/dist", "${configDir}/node_modules"]
+1 -1
View File
@@ -13,4 +13,4 @@ export * from "./telemetry"
export const MEDUSA_CLI_PATH = require.resolve("@medusajs/medusa-cli") export const MEDUSA_CLI_PATH = require.resolve("@medusajs/medusa-cli")
export { GraphQLSchema, gqlSchemaToTypes, Query } from "@medusajs/modules-sdk" export { Query } from "@medusajs/modules-sdk"
-1
View File
@@ -44,7 +44,6 @@
"@graphql-tools/schema": "^10.0.0", "@graphql-tools/schema": "^10.0.0",
"@medusajs/orchestration": "^0.5.7", "@medusajs/orchestration": "^0.5.7",
"@medusajs/utils": "^1.11.9", "@medusajs/utils": "^1.11.9",
"graphql": "^16.6.0",
"resolve-cwd": "^3.0.0" "resolve-cwd": "^3.0.0"
}, },
"peerDependencies": { "peerDependencies": {
+3 -4
View File
@@ -20,6 +20,7 @@ import {
ContainerRegistrationKeys, ContainerRegistrationKeys,
createMedusaContainer, createMedusaContainer,
dynamicImport, dynamicImport,
GraphQLUtils,
isObject, isObject,
isString, isString,
MedusaError, MedusaError,
@@ -29,7 +30,6 @@ import {
} from "@medusajs/utils" } from "@medusajs/utils"
import type { Knex } from "@mikro-orm/knex" import type { Knex } from "@mikro-orm/knex"
import { asValue } from "awilix" import { asValue } from "awilix"
import { GraphQLSchema } from "graphql/type"
import { MODULE_PACKAGE_NAMES } from "./definitions" import { MODULE_PACKAGE_NAMES } from "./definitions"
import { import {
MedusaModule, MedusaModule,
@@ -39,7 +39,6 @@ import {
import { RemoteLink } from "./remote-link" import { RemoteLink } from "./remote-link"
import { createQuery, RemoteQuery } from "./remote-query" import { createQuery, RemoteQuery } from "./remote-query"
import { MODULE_RESOURCE_TYPE, MODULE_SCOPE } from "./types" import { MODULE_RESOURCE_TYPE, MODULE_SCOPE } from "./types"
import { cleanGraphQLSchema } from "./utils"
const LinkModulePackage = MODULE_PACKAGE_NAMES[Modules.LINK] const LinkModulePackage = MODULE_PACKAGE_NAMES[Modules.LINK]
@@ -204,7 +203,7 @@ function cleanAndMergeSchema(loadedSchema) {
scalar DateTime scalar DateTime
scalar JSON scalar JSON
` `
const { schema: cleanedSchema, notFound } = cleanGraphQLSchema( const { schema: cleanedSchema, notFound } = GraphQLUtils.cleanGraphQLSchema(
defaultMedusaSchema + loadedSchema defaultMedusaSchema + loadedSchema
) )
const mergedSchema = mergeTypeDefs(cleanedSchema) const mergedSchema = mergeTypeDefs(cleanedSchema)
@@ -232,7 +231,7 @@ export type MedusaAppOutput = {
link: RemoteLink | undefined link: RemoteLink | undefined
query: RemoteQueryFunction query: RemoteQueryFunction
entitiesMap?: Record<string, any> entitiesMap?: Record<string, any>
gqlSchema?: GraphQLSchema gqlSchema?: GraphQLUtils.GraphQLSchema
notFound?: Record<string, Record<string, string>> notFound?: Record<string, Record<string, string>>
runMigrations: RunMigrationFn runMigrations: RunMigrationFn
revertMigrations: RevertMigrationFn revertMigrations: RevertMigrationFn
@@ -1,6 +1,6 @@
import { mergeTypeDefs } from "@graphql-tools/merge" import { mergeTypeDefs } from "@graphql-tools/merge"
import { makeExecutableSchema } from "@graphql-tools/schema" import { makeExecutableSchema } from "@graphql-tools/schema"
import { cleanGraphQLSchema } from "../../utils/clean-graphql-schema" import { cleanGraphQLSchema } from "@medusajs/utils"
export function getEntitiesMap(loadedSchema): Map<string, any> { export function getEntitiesMap(loadedSchema): Map<string, any> {
const defaultMedusaSchema = ` const defaultMedusaSchema = `
@@ -7,5 +7,3 @@ export enum MODULE_RESOURCE_TYPE {
SHARED = "shared", SHARED = "shared",
ISOLATED = "isolated", ISOLATED = "isolated",
} }
export { GraphQLSchema } from "graphql"
+2 -4
View File
@@ -1,4 +1,2 @@
export * from "./clean-graphql-schema" export * from "./linking-error"
export * from "./graphql-schema-to-fields" export * from "./convert-data-to-link-definition"
export * from "./gql-schema-to-types"
export * from "./gql-get-fields-and-relations"
+1 -2
View File
@@ -33,8 +33,7 @@
"typescript": "^5.6.2" "typescript": "^5.6.2"
}, },
"dependencies": { "dependencies": {
"@medusajs/utils": "^1.11.9", "@medusajs/utils": "^1.11.9"
"graphql": "^16.6.0"
}, },
"peerDependencies": { "peerDependencies": {
"awilix": "^8.0.1" "awilix": "^8.0.1"
@@ -10,12 +10,11 @@ import {
} from "@medusajs/types" } from "@medusajs/types"
import { import {
deduplicate, deduplicate,
extractRelationsFromGQL, GraphQLUtils,
isDefined, isDefined,
isString, isString,
MedusaError, MedusaError,
} from "@medusajs/utils" } from "@medusajs/utils"
import GraphQLParser from "./graphql-ast"
const BASE_PATH = "_root" const BASE_PATH = "_root"
@@ -140,7 +139,7 @@ export class RemoteJoiner {
graphqlQuery: string, graphqlQuery: string,
variables?: Record<string, unknown> variables?: Record<string, unknown>
): RemoteJoinerQuery { ): RemoteJoinerQuery {
const parser = new GraphQLParser(graphqlQuery, variables) const parser = new GraphQLUtils.GraphQLParser(graphqlQuery, variables)
return parser.parseQuery() return parser.parseQuery()
} }
@@ -154,7 +153,9 @@ export class RemoteJoiner {
) { ) {
this.options.autoCreateServiceNameAlias ??= true this.options.autoCreateServiceNameAlias ??= true
if (this.options.entitiesMap) { if (this.options.entitiesMap) {
this.entityMap = extractRelationsFromGQL(this.options.entitiesMap) this.entityMap = GraphQLUtils.extractRelationsFromGQL(
this.options.entitiesMap
)
} }
this.buildReferences( this.buildReferences(
+2
View File
@@ -36,6 +36,8 @@
"typescript": "^5.6.2" "typescript": "^5.6.2"
}, },
"dependencies": { "dependencies": {
"@graphql-tools/merge": "^9.0.7",
"@graphql-tools/schema": "^10.0.6",
"@medusajs/types": "^1.11.16", "@medusajs/types": "^1.11.16",
"@mikro-orm/core": "5.9.7", "@mikro-orm/core": "5.9.7",
"@mikro-orm/migrations": "5.9.7", "@mikro-orm/migrations": "5.9.7",
+1
View File
@@ -17,3 +17,4 @@ export * as PromotionUtils from "./promotion"
export * as SearchUtils from "./search" export * as SearchUtils from "./search"
export * as ShippingProfileUtils from "./shipping" export * as ShippingProfileUtils from "./shipping"
export * as UserUtils from "./user" export * as UserUtils from "./user"
export * as GraphQLUtils from "./graphql"
-1
View File
@@ -26,7 +26,6 @@ export * from "./get-node-version"
export * from "./get-selects-and-relations-from-object-array" export * from "./get-selects-and-relations-from-object-array"
export * from "./get-set-difference" export * from "./get-set-difference"
export * from "./graceful-shutdown-server" export * from "./graceful-shutdown-server"
export * from "./graphql-relations-entity-map"
export * from "./group-by" export * from "./group-by"
export * from "./handle-postgres-database-error" export * from "./handle-postgres-database-error"
export * from "./is-big-number" export * from "./is-big-number"
@@ -1,4 +1,4 @@
import { cleanGraphQLSchema } from "../utils/clean-graphql-schema" import { cleanGraphQLSchema } from "../clean-graphql"
describe("Clean Graphql Schema", function () { describe("Clean Graphql Schema", function () {
it("Should keep the schema intact if all entities are available", function () { it("Should keep the schema intact if all entities are available", function () {
@@ -1,4 +1,4 @@
import GraphQLParser from "../../joiner/graphql-ast" import { GraphQLParser } from "../graphql-parser"
describe("RemoteJoiner.parseQuery", () => { describe("RemoteJoiner.parseQuery", () => {
beforeEach(() => { beforeEach(() => {
@@ -1,6 +1,6 @@
import { mergeTypeDefs } from "@graphql-tools/merge" import { mergeTypeDefs } from "@graphql-tools/merge"
import { makeExecutableSchema } from "@graphql-tools/schema" import { makeExecutableSchema } from "@graphql-tools/schema"
import { gqlGetFieldsAndRelations } from "../../utils" import { gqlGetFieldsAndRelations } from "../../get-fields-and-relations"
const userModule = ` const userModule = `
type User { type User {
@@ -1,6 +1,6 @@
import { mergeTypeDefs } from "@graphql-tools/merge" import { mergeTypeDefs } from "@graphql-tools/merge"
import { makeExecutableSchema } from "@graphql-tools/schema" import { makeExecutableSchema } from "@graphql-tools/schema"
import { graphqlSchemaToFields } from "../../utils" import { graphqlSchemaToFields } from "../../graphql-to-fields"
const userModule = ` const userModule = `
type User { type User {
@@ -28,7 +28,10 @@ interface Entity {
directives?: { [field: string]: Directive[] } directives?: { [field: string]: Directive[] }
} }
class GraphQLParser { /**
* Remote joiner graphql parser
*/
export class GraphQLParser {
private ast: DocumentNode private ast: DocumentNode
constructor(input: string, private variables: Record<string, unknown> = {}) { constructor(input: string, private variables: Record<string, unknown> = {}) {
@@ -190,5 +193,3 @@ class GraphQLParser {
return remoteJoinConfig return remoteJoinConfig
} }
} }
export default GraphQLParser
@@ -1,16 +1,19 @@
import { MedusaModule } from "../medusa-module"
import { FileSystem, toCamelCase } from "@medusajs/utils" import { FileSystem, toCamelCase } from "@medusajs/utils"
import { GraphQLSchema } from "graphql/type" import { GraphQLSchema } from "graphql/type"
import { parse, printSchema } from "graphql" import { parse, printSchema } from "graphql"
import { codegen } from "@graphql-codegen/core" import { codegen } from "@graphql-codegen/core"
import * as typescriptPlugin from "@graphql-codegen/typescript" import * as typescriptPlugin from "@graphql-codegen/typescript"
import { ModuleJoinerConfig } from "@medusajs/types"
function buildEntryPointsTypeMap( function buildEntryPointsTypeMap({
schema,
joinerConfigs,
}: {
schema: string schema: string
): { entryPoint: string; entityType: any }[] { joinerConfigs: ModuleJoinerConfig[]
}): { entryPoint: string; entityType: any }[] {
// build map entry point to there type to be merged and used by the remote query // build map entry point to there type to be merged and used by the remote query
const joinerConfigs = MedusaModule.getAllJoinerConfigs()
return joinerConfigs return joinerConfigs
.flatMap((config) => { .flatMap((config) => {
const aliases = Array.isArray(config.alias) const aliases = Array.isArray(config.alias)
@@ -41,15 +44,17 @@ async function generateTypes({
outputDir, outputDir,
filename, filename,
config, config,
joinerConfigs,
}: { }: {
outputDir: string outputDir: string
filename: string filename: string
config: Parameters<typeof codegen>[0] config: Parameters<typeof codegen>[0]
joinerConfigs: ModuleJoinerConfig[]
}) { }) {
const fileSystem = new FileSystem(outputDir) const fileSystem = new FileSystem(outputDir)
let output = await codegen(config) let output = await codegen(config)
const entryPoints = buildEntryPointsTypeMap(output) const entryPoints = buildEntryPointsTypeMap({ schema: output, joinerConfigs })
const interfaceName = toCamelCase(filename) const interfaceName = toCamelCase(filename)
@@ -81,14 +86,17 @@ ${entryPoints
} }
} }
// TODO: rename from gqlSchemaToTypes to grapthqlToTsTypes
export async function gqlSchemaToTypes({ export async function gqlSchemaToTypes({
schema, schema,
outputDir, outputDir,
filename, filename,
joinerConfigs,
}: { }: {
schema: GraphQLSchema schema: GraphQLSchema
outputDir: string outputDir: string
filename: string filename: string
joinerConfigs: ModuleJoinerConfig[]
}) { }) {
const config = { const config = {
documents: [], documents: [],
@@ -114,5 +122,5 @@ export async function gqlSchemaToTypes({
}, },
} }
await generateTypes({ outputDir, filename, config }) await generateTypes({ outputDir, filename, config, joinerConfigs })
} }
+9
View File
@@ -0,0 +1,9 @@
export * from "./graphql-parser"
export * from "./graphql-to-fields"
export * from "./extract-relations-from-graphql"
export * from "./clean-graphql"
export * from "./graphql-to-ts-types"
export * from "./get-fields-and-relations"
export * from "graphql"
export * from "graphql/type"
+1
View File
@@ -1,3 +1,4 @@
export * from "./graphql"
export * from "./api-key" export * from "./api-key"
export * from "./auth" export * from "./auth"
export * from "./bundles" export * from "./bundles"
+4 -2
View File
@@ -3,11 +3,12 @@ import express from "express"
import { track } from "medusa-telemetry" import { track } from "medusa-telemetry"
import { scheduleJob } from "node-schedule" import { scheduleJob } from "node-schedule"
import { GracefulShutdownServer } from "@medusajs/utils" import { gqlSchemaToTypes, GracefulShutdownServer } from "@medusajs/utils"
import http, { IncomingMessage, ServerResponse } from "http" import http, { IncomingMessage, ServerResponse } from "http"
import { gqlSchemaToTypes, logger } from "@medusajs/framework" import { logger } from "@medusajs/framework"
import loaders from "../loaders" import loaders from "../loaders"
import { MedusaModule } from "@medusajs/modules-sdk"
const EVERY_SIXTH_HOUR = "0 */6 * * *" const EVERY_SIXTH_HOUR = "0 */6 * * *"
const CRON_SCHEDULE = EVERY_SIXTH_HOUR const CRON_SCHEDULE = EVERY_SIXTH_HOUR
@@ -66,6 +67,7 @@ async function start({ port, directory, types }) {
outputDir: outputDirGeneratedTypes, outputDir: outputDirGeneratedTypes,
filename: "remote-query-entry-points", filename: "remote-query-entry-points",
schema: gqlSchema, schema: gqlSchema,
joinerConfigs: MedusaModule.getAllJoinerConfigs(),
}) })
logger.info("Geneated modules types") logger.info("Geneated modules types")
} }
+1 -2
View File
@@ -1,5 +1,5 @@
import { ConfigModule, MedusaContainer, PluginDetails } from "@medusajs/types" import { ConfigModule, MedusaContainer, PluginDetails } from "@medusajs/types"
import { ContainerRegistrationKeys, promiseAll } from "@medusajs/utils" import { ContainerRegistrationKeys, promiseAll, GraphQLSchema } from "@medusajs/utils"
import { asValue } from "awilix" import { asValue } from "awilix"
import { Express, NextFunction, Request, Response } from "express" import { Express, NextFunction, Request, Response } from "express"
import { join } from "path" import { join } from "path"
@@ -12,7 +12,6 @@ import {
container, container,
expressLoader, expressLoader,
featureFlagsLoader, featureFlagsLoader,
GraphQLSchema,
JobLoader, JobLoader,
LinkLoader, LinkLoader,
logger, logger,
@@ -1,18 +1,13 @@
import { makeExecutableSchema } from "@graphql-tools/schema" import { makeExecutableSchema } from "@graphql-tools/schema"
import { import { MedusaModule } from "@medusajs/modules-sdk"
cleanGraphQLSchema,
gqlGetFieldsAndRelations,
MedusaModule,
} from "@medusajs/modules-sdk"
import { import {
IndexTypes, IndexTypes,
JoinerServiceConfigAlias, JoinerServiceConfigAlias,
ModuleJoinerConfig, ModuleJoinerConfig,
ModuleJoinerRelationship, ModuleJoinerRelationship,
} from "@medusajs/types" } from "@medusajs/types"
import { CommonEvents } from "@medusajs/utils" import { CommonEvents, GraphQLUtils } from "@medusajs/utils"
import { schemaObjectRepresentationPropertiesToOmit } from "@types" import { schemaObjectRepresentationPropertiesToOmit } from "@types"
import { Kind, ObjectTypeDefinitionNode } from "graphql/index"
export const CustomDirectives = { export const CustomDirectives = {
Listeners: { Listeners: {
@@ -25,7 +20,7 @@ export const CustomDirectives = {
} }
export function makeSchemaExecutable(inputSchema: string) { export function makeSchemaExecutable(inputSchema: string) {
const { schema: cleanedSchema } = cleanGraphQLSchema(inputSchema) const { schema: cleanedSchema } = GraphQLUtils.cleanGraphQLSchema(inputSchema)
return makeExecutableSchema({ typeDefs: cleanedSchema }) return makeExecutableSchema({ typeDefs: cleanedSchema })
} }
@@ -330,7 +325,7 @@ function processEntity(
) )
currentObjectRepresentationRef.fields = currentObjectRepresentationRef.fields =
gqlGetFieldsAndRelations(entitiesMap, entityName) ?? [] GraphQLUtils.gqlGetFieldsAndRelations(entitiesMap, entityName) ?? []
/** /**
* Retrieve the module and alias for the current entity. * Retrieve the module and alias for the current entity.
@@ -372,14 +367,16 @@ function processEntity(
const schemaParentEntity = Object.values(entitiesMap).filter((value: any) => { const schemaParentEntity = Object.values(entitiesMap).filter((value: any) => {
return ( return (
value.astNode && value.astNode &&
(value.astNode as ObjectTypeDefinitionNode).fields?.some((field: any) => { (value.astNode as GraphQLUtils.ObjectTypeDefinitionNode).fields?.some(
(field: any) => {
let currentType = field.type let currentType = field.type
while (currentType.type) { while (currentType.type) {
currentType = currentType.type currentType = currentType.type
} }
return currentType.name?.value === entityName return currentType.name?.value === entityName
}) }
)
) )
}) })
@@ -410,7 +407,7 @@ function processEntity(
}) })
const isEntityListInParent = const isEntityListInParent =
entityFieldInParent.type.kind === Kind.LIST_TYPE entityFieldInParent.type.kind === GraphQLUtils.Kind.LIST_TYPE
const entityTargetPropertyNameInParent = entityFieldInParent.name.value const entityTargetPropertyNameInParent = entityFieldInParent.name.value
/** /**
@@ -1,10 +1,9 @@
import { join } from "path" import { join } from "path"
import { CustomDirectives, makeSchemaExecutable } from "./build-config" import { CustomDirectives, makeSchemaExecutable } from "./build-config"
import { import {
gqlSchemaToTypes as ModulesSdkGqlSchemaToTypes,
MedusaModule, MedusaModule,
} from "@medusajs/modules-sdk" } from "@medusajs/modules-sdk"
import { FileSystem } from "@medusajs/utils" import { FileSystem, gqlSchemaToTypes as ModulesSdkGqlSchemaToTypes, } from "@medusajs/utils"
import * as process from "process" import * as process from "process"
export async function gqlSchemaToTypes(schema: string) { export async function gqlSchemaToTypes(schema: string) {
@@ -18,6 +17,7 @@ export async function gqlSchemaToTypes(schema: string) {
schema: executableSchema, schema: executableSchema,
filename, filename,
outputDir: dir, outputDir: dir,
joinerConfigs: MedusaModule.getAllJoinerConfigs(),
}) })
const fileSystem = new FileSystem(dir) const fileSystem = new FileSystem(dir)
+5 -5
View File
@@ -4535,7 +4535,7 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"@graphql-tools/merge@npm:^9.0.6": "@graphql-tools/merge@npm:^9.0.6, @graphql-tools/merge@npm:^9.0.7":
version: 9.0.7 version: 9.0.7
resolution: "@graphql-tools/merge@npm:9.0.7" resolution: "@graphql-tools/merge@npm:9.0.7"
dependencies: dependencies:
@@ -4611,7 +4611,7 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"@graphql-tools/schema@npm:^10.0.3, @graphql-tools/schema@npm:^10.0.4": "@graphql-tools/schema@npm:^10.0.3, @graphql-tools/schema@npm:^10.0.4, @graphql-tools/schema@npm:^10.0.6":
version: 10.0.6 version: 10.0.6
resolution: "@graphql-tools/schema@npm:10.0.6" resolution: "@graphql-tools/schema@npm:10.0.6"
dependencies: dependencies:
@@ -6249,7 +6249,6 @@ __metadata:
"@medusajs/types": ^1.11.16 "@medusajs/types": ^1.11.16
"@medusajs/utils": ^1.11.9 "@medusajs/utils": ^1.11.9
cross-env: ^5.2.1 cross-env: ^5.2.1
graphql: ^16.6.0
jest: ^29.7.0 jest: ^29.7.0
resolve-cwd: ^3.0.0 resolve-cwd: ^3.0.0
rimraf: ^5.0.1 rimraf: ^5.0.1
@@ -6326,7 +6325,6 @@ __metadata:
"@medusajs/types": ^1.11.16 "@medusajs/types": ^1.11.16
"@medusajs/utils": ^1.11.9 "@medusajs/utils": ^1.11.9
cross-env: ^5.2.1 cross-env: ^5.2.1
graphql: ^16.6.0
jest: ^29.7.0 jest: ^29.7.0
rimraf: ^5.0.1 rimraf: ^5.0.1
typescript: ^5.6.2 typescript: ^5.6.2
@@ -6741,6 +6739,8 @@ __metadata:
version: 0.0.0-use.local version: 0.0.0-use.local
resolution: "@medusajs/utils@workspace:packages/core/utils" resolution: "@medusajs/utils@workspace:packages/core/utils"
dependencies: dependencies:
"@graphql-tools/merge": ^9.0.7
"@graphql-tools/schema": ^10.0.6
"@medusajs/types": ^1.11.16 "@medusajs/types": ^1.11.16
"@mikro-orm/core": 5.9.7 "@mikro-orm/core": 5.9.7
"@mikro-orm/migrations": 5.9.7 "@mikro-orm/migrations": 5.9.7
@@ -21410,7 +21410,7 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"graphql@npm:^16.6.0, graphql@npm:^16.8.1": "graphql@npm:^16.8.1":
version: 16.8.1 version: 16.8.1
resolution: "graphql@npm:16.8.1" resolution: "graphql@npm:16.8.1"
checksum: 129c318156b466f440914de80dbf7bc67d17f776f2a088a40cb0da611d19a97c224b1c6d2b13cbcbc6e5776e45ed7468b8432f9c3536724e079b44f1a3d57a8a checksum: 129c318156b466f440914de80dbf7bc67d17f776f2a088a40cb0da611d19a97c224b1c6d2b13cbcbc6e5776e45ed7468b8432f9c3536724e079b44f1a3d57a8a