breaking: remove deprecated commands and code (#9521)

* breaking: remove deprecated commands

* feat: remove deprecated code and usages

* refactor: remove more logic around default relations

* fix tests

* remove log

* fix: remove defaultFields usage

* fix: add back accidentally removed code

* refactor: implement feedback

* feat: add --cluster flag to the start command

* refactor: assign limit to defaultLimit property

* fix: breaking code because of removed check

---------

Co-authored-by: adrien2p <adrien.deperetti@gmail.com>
This commit is contained in:
Harminder Virk
2024-10-14 20:11:34 +05:30
committed by GitHub
co-authored by adrien2p
parent cea4cdc8d7
commit ad322f2760
37 changed files with 162 additions and 679 deletions
+6 -97
View File
@@ -1,7 +1,6 @@
import { sync as existsSync } from "fs-exists-cached"
import { setTelemetryEnabled } from "medusa-telemetry"
import path from "path"
import resolveCwd from "resolve-cwd"
import { newStarter } from "./commands/new"
import { didYouMean } from "./did-you-mean"
@@ -278,66 +277,6 @@ function buildLocalCommands(cli, isLocalProject) {
)
}),
})
.command({
command: `seed`,
desc: `Migrates and populates the database with the provided file.`,
builder: (_) =>
_.option(`f`, {
alias: `seed-file`,
type: `string`,
describe: `Path to the file where the seed is defined.`,
required: true,
}).option(`m`, {
alias: `migrate`,
type: `boolean`,
default: true,
describe: `Flag to indicate if migrations should be run prior to seeding the database`,
}),
handler: handlerP(
getCommandHandler(`seed`, (args, cmd) => {
process.env.NODE_ENV ??= `development`
return cmd(args)
})
),
})
.command({
command: `migrations [action] [modules...]`,
desc: `Manage migrations from the core and your own project`,
builder: {
action: {
demand: true,
description: "The action to perform on migrations",
choices: ["run", "revert", "show", "generate"],
},
modules: {
description: "Modules for which to run the action (revert, generate)",
demand: false,
},
},
handler: handlerP(
getCommandHandler(`migrate`, (args, cmd) => {
process.env.NODE_ENV = process.env.NODE_ENV || `development`
return cmd(args)
})
),
})
.command({
command: `links [action]`,
desc: `Manage migrations for the links from the core, your project and packages`,
builder: {
action: {
demand: true,
description: "The action to perform on links",
choices: ["sync"],
},
},
handler: handlerP(
getCommandHandler(`links`, (args, cmd) => {
process.env.NODE_ENV = process.env.NODE_ENV || `development`
return cmd(args)
})
),
})
.command({
command: `develop`,
desc: `Start development server. Watches file and rebuilds when something changes`,
@@ -397,6 +336,12 @@ function buildLocalCommands(cli, isLocalProject) {
describe: process.env.PORT
? `Set port. Defaults to ${process.env.PORT} (set by env.PORT) (otherwise defaults ${defaultPort})`
: `Set port. Defaults to ${defaultPort}`,
})
.option(`cluster`, {
type: `number`,
default: process.env.CPUS,
describe:
"Start the Node.js server in cluster mode. You can specify the number of cpus to use, which defaults to (env.CPUS)",
}),
handler: handlerP(
getCommandHandler(`start`, (args, cmd) => {
@@ -422,42 +367,6 @@ function buildLocalCommands(cli, isLocalProject) {
})
),
})
.command({
command: `start-cluster`,
desc: `Start development server in cluster mode (beta).`,
builder: (_) =>
_.option(`H`, {
alias: `host`,
type: `string`,
default: defaultHost,
describe: `Set host. Defaults to ${defaultHost}`,
})
.option(`p`, {
alias: `port`,
type: `string`,
default: process.env.PORT || defaultPort,
describe: process.env.PORT
? `Set port. Defaults to ${process.env.PORT} (set by env.PORT) (otherwise defaults ${defaultPort})`
: `Set port. Defaults to ${defaultPort}`,
})
.option(`c`, {
alias: `cpus`,
type: `number`,
default: process.env.CPUS,
describe:
"Set number of cpus to use. Defaults to max number of cpus available on the system (set by env.CPUS)",
}),
handler: handlerP(
getCommandHandler(`start-cluster`, (args, cmd) => {
process.env.NODE_ENV = process.env.NODE_ENV || `development`
cmd(args)
// Return an empty promise to prevent handlerP from exiting early.
// The development server shouldn't ever exit until the user directly
// kills it so this is fine.
return new Promise((resolve) => {})
})
),
})
.command({
command: `user`,
desc: `Create a user`,
@@ -256,15 +256,6 @@ export type ProjectConfigOptions = {
*/
databaseLogging?: boolean
/**
* @ignore
* @deprecated
*
* @privateRemarks
* only postgres is supported, so this config has no effect
*/
databaseType?: string
/**
* This configuration is used to pass additional options to the database connection. You can pass any configuration. For example, pass the
* `ssl` property that enables support for TLS/SSL connections.
@@ -391,19 +382,6 @@ export type ProjectConfigOptions = {
*/
sessionOptions?: SessionOptions
/**
* This property configures the HTTP compression from the application layer. If you have access to the HTTP server, the recommended approach would be to enable it there.
* However, some platforms don't offer access to the HTTP layer and in those cases, this is a good alternative.
*
* If you enable HTTP compression and you want to disable it for specific API Routes, you can pass in the request header `"x-no-compression": true`.
*
* @ignore
*
* @deprecated use {@link http }'s `compression` property instead.
*
*/
httpCompression?: HttpCompressionOptions
/**
* Configure the number of staged jobs that are polled from the database. Default is `1000`.
*
@@ -1,7 +1,7 @@
import z from "zod"
import { MedusaError } from "@medusajs/utils"
import { validateAndTransformQuery } from "../utils/validate-query"
import { MedusaRequest, MedusaResponse, MedusaNextFunction } from "../types"
import { MedusaNextFunction, MedusaRequest, MedusaResponse } from "../types"
export const createSelectParams = () => {
return z.object({
@@ -124,7 +124,7 @@ describe("validateAndTransformQuery", () => {
}
let queryConfig: any = {
defaultFields: [
defaults: [
"id",
"created_at",
"updated_at",
@@ -134,12 +134,6 @@ describe("validateAndTransformQuery", () => {
"metadata.children.id",
"metadata.product.id",
],
defaultRelations: [
"metadata",
"metadata.parent",
"metadata.children",
"metadata.product",
],
isList: true,
}
@@ -216,7 +210,7 @@ describe("validateAndTransformQuery", () => {
const nextFunction: MedusaNextFunction = jest.fn()
let queryConfig: any = {
defaultFields: [
defaults: [
"id",
"created_at",
"updated_at",
@@ -226,12 +220,6 @@ describe("validateAndTransformQuery", () => {
"metadata.children.id",
"metadata.product.id",
],
defaultRelations: [
"metadata",
"metadata.parent",
"metadata.children",
"metadata.product",
],
isList: true,
}
@@ -252,7 +240,7 @@ describe("validateAndTransformQuery", () => {
} as unknown as MedusaRequest
queryConfig = {
defaultFields: [
defaults: [
"id",
"prop-test-something",
"created_at",
@@ -263,12 +251,6 @@ describe("validateAndTransformQuery", () => {
"metadata.children.id",
"metadata.product.id",
],
defaultRelations: [
"metadata",
"metadata.parent",
"metadata.children",
"metadata.product",
],
isList: true,
}
@@ -415,7 +397,7 @@ describe("validateAndTransformQuery", () => {
} as unknown as MedusaRequest
queryConfig = {
defaultFields: [
defaults: [
"id",
"created_at",
"deleted_at",
@@ -467,7 +449,7 @@ describe("validateAndTransformQuery", () => {
const nextFunction: MedusaNextFunction = jest.fn()
let queryConfig: any = {
defaultFields: [
defaults: [
"id",
"created_at",
"updated_at",
@@ -514,7 +496,7 @@ describe("validateAndTransformQuery", () => {
} as unknown as MedusaRequest
queryConfig = {
defaultFields: [
defaults: [
"id",
"created_at",
"updated_at",
@@ -561,7 +543,7 @@ describe("validateAndTransformQuery", () => {
} as unknown as MedusaRequest
queryConfig = {
defaultFields: [
defaults: [
"id",
"created_at",
"deleted_at",
+2 -7
View File
@@ -123,15 +123,10 @@ export interface MedusaRequest<Body = unknown>
*/
filterableFields: Record<string, unknown>
includes?: Record<string, boolean>
/**
* An array of fields and relations that are allowed to be queried, this can be set by the
* consumer as part of a middleware and it will take precedence over the defaultAllowedFields
* @deprecated use `allowed` instead
*/
allowedFields?: string[]
/**
* An array of fields and relations that are allowed to be queried, this can be set by the
* consumer as part of a middleware and it will take precedence over the defaultAllowedFields set
* consumer as part of a middleware and it will take precedence over the req.allowed set
* by the api
*/
allowed?: string[]
@@ -4,7 +4,6 @@ import {
isDefined,
isPresent,
MedusaError,
getSetDifference,
stringToSelectRelationObject,
} from "@medusajs/utils"
@@ -28,28 +27,15 @@ export function prepareListQuery<T extends RequestQueryFields, TEntity>(
validated: T,
queryConfig: QueryConfig<TEntity> = {}
) {
// TODO: this function will be simplified a lot once we drop support for the old api
const { order, fields, limit = 50, expand, offset = 0 } = validated
let {
allowed = [],
defaults = [],
defaultFields = [],
defaultLimit,
allowedFields = [],
allowedRelations = [],
defaultRelations = [],
isList,
} = queryConfig
allowedFields = allowed.length ? allowed : allowedFields
defaultFields = defaults.length ? defaults : defaultFields
let { allowed = [], defaults = [], defaultLimit = 50, isList } = queryConfig
const { order, fields, limit = defaultLimit, offset = 0 } = validated
// e.g *product.variants meaning that we want all fields from the product.variants
// in that case it wont be part of the select but it will be part of the relations.
// For the remote query we will have to add the fields to the fields array as product.variants.*
const starFields: Set<string> = new Set()
let allFields = new Set(defaultFields) as Set<string>
let allFields = new Set(defaults) as Set<string>
if (isDefined(fields)) {
const customFields = fields.split(",").filter(Boolean)
@@ -90,9 +76,9 @@ export function prepareListQuery<T extends RequestQueryFields, TEntity>(
const notAllowedFields: string[] = []
if (allowedFields.length) {
if (allowed.length) {
;[...allFields, ...Array.from(starFields)].forEach((field) => {
const hasAllowedField = allowedFields.includes(field)
const hasAllowedField = allowed.includes(field)
if (hasAllowedField) {
return
@@ -108,7 +94,7 @@ export function prepareListQuery<T extends RequestQueryFields, TEntity>(
return
}
const fieldStartsWithAllowedField = allowedFields.some((allowedField) =>
const fieldStartsWithAllowedField = allowed.some((allowedField) =>
field.startsWith(allowedField)
)
@@ -133,33 +119,8 @@ export function prepareListQuery<T extends RequestQueryFields, TEntity>(
Array.from(allFields)
)
let allRelations = new Set([
...relations,
...defaultRelations,
...Array.from(starFields),
])
let allRelations = new Set([...relations, ...Array.from(starFields)])
if (isDefined(expand)) {
allRelations = new Set(expand.split(",").filter(Boolean))
}
if (allowedRelations.length && expand) {
const allAllowedRelations = new Set([...allowedRelations])
const notAllowedRelations = getSetDifference(
allRelations,
allAllowedRelations
)
if (allRelations.size && notAllowedRelations.size) {
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
`Requested fields [${Array.from(notAllowedRelations).join(
", "
)}] are not valid`
)
}
}
// End of expand compatibility
let orderBy: { [k: symbol]: "DESC" | "ASC" } | undefined = {}
@@ -173,10 +134,7 @@ export function prepareListQuery<T extends RequestQueryFields, TEntity>(
orderBy = { [order]: "ASC" }
}
if (
queryConfig?.allowedFields?.length &&
!queryConfig?.allowedFields.includes(orderField)
) {
if (allowed.length && !allowed.includes(orderField)) {
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
`Order field ${orderField} is not valid`
@@ -190,7 +148,7 @@ export function prepareListQuery<T extends RequestQueryFields, TEntity>(
select: select.length ? select : undefined,
relations: Array.from(allRelations),
skip: offset,
take: limit ?? defaultLimit,
take: limit,
order: finalOrder,
},
remoteQueryConfig: {
@@ -202,7 +160,7 @@ export function prepareListQuery<T extends RequestQueryFields, TEntity>(
pagination: isList
? {
skip: offset,
take: limit ?? defaultLimit,
take: limit,
order: finalOrder,
}
: {},
@@ -1,7 +1,7 @@
import { z } from "zod"
import { omit } from "lodash"
import { NextFunction } from "express"
import { removeUndefinedProperties, MedusaError } from "@medusajs/utils"
import { MedusaError, removeUndefinedProperties } from "@medusajs/utils"
import { BaseEntity, QueryConfig, RequestQueryFields } from "@medusajs/types"
import { zodValidator } from "../../zod/zod-helpers"
-22
View File
@@ -119,12 +119,6 @@ export type TotalField =
* Fields that can be passed in the query parameters of a request.
*/
export type RequestQueryFields = {
/**
* Comma-separated relations that should be expanded in the returned data.
* @deprecated Use `fields` instead and the relations will be inferred
*/
expand?: string
/**
* Comma-separated fields that should be included in the returned data.
* if a field is prefixed with `+` it will be added to the default fields, using `-` will remove it from the default fields.
@@ -309,26 +303,10 @@ export type QueryConfig<TEntity> = {
* Default fields and relations to return
*/
defaults?: (keyof TEntity | string)[]
/**
* @deprecated Use `defaults` instead
*/
defaultFields?: (keyof TEntity | string)[]
/**
* @deprecated Use `defaultFields` instead and the relations will be inferred
*/
defaultRelations?: string[]
/**
* Fields and relations that are allowed to be requested
*/
allowed?: string[]
/**
* @deprecated Use `allowed` instead
*/
allowedFields?: string[]
/**
* @deprecated Use `allowedFields` instead and the relations will be inferred
*/
allowedRelations?: string[]
defaultLimit?: number
isList?: boolean
}
@@ -265,15 +265,6 @@ export type ProjectConfigOptions = {
*/
databaseLogging?: boolean
/**
* @ignore
* @deprecated
*
* @privateRemarks
* only postgres is supported, so this config has no effect
*/
databaseType?: string
/**
* This configuration is used to pass additional options to the database connection. You can pass any configuration. For example, pass the
* `ssl` property that enables support for TLS/SSL connections.
@@ -400,19 +391,6 @@ export type ProjectConfigOptions = {
*/
sessionOptions?: SessionOptions
/**
* This property configures the HTTP compression from the application layer. If you have access to the HTTP server, the recommended approach would be to enable it there.
* However, some platforms don't offer access to the HTTP layer and in those cases, this is a good alternative.
*
* If you enable HTTP compression and you want to disable it for specific API Routes, you can pass in the request header `"x-no-compression": true`.
*
* @ignore
*
* @deprecated use {@link http }'s `compression` property instead.
*
*/
httpCompression?: HttpCompressionOptions
/**
* Configure the number of staged jobs that are polled from the database. Default is `1000`.
*
-17
View File
@@ -1,23 +1,6 @@
import { EventBusTypes } from "./bundles"
import { Message } from "./event-bus"
/**
* @deprecated use `Context` instead
* @interface
*
* A context used to share resources, such as transaction manager, between the application and the module.
*/
export type SharedContext = {
/**
* An instance of a transaction manager.
*/
transactionManager?: any
/**
* An instance of an entity manager.
*/
manager?: any
}
export interface MessageAggregatorFormat {
groupBy?: string[]
sortBy?: { [key: string]: string[] | string | number }
-1
View File
@@ -1,7 +1,6 @@
export * as ApiKeyUtils from "./api-key"
export * as CoreFlowsUitls from "./core-flows"
export * as DALUtils from "./dal"
export * as DecoratorUtils from "./decorators"
export * as DefaultsUtils from "./defaults"
export * as DMLUtils from "./dml"
export * as EventBusUtils from "./event-bus"
@@ -1 +0,0 @@
export * from "./inject-entity-manager"
@@ -1,50 +0,0 @@
import { Context, SharedContext } from "@medusajs/types"
import { MedusaContextType } from "../modules-sdk/decorators"
// @deprecated Use InjectManager instead
export function InjectEntityManager(
shouldForceTransaction: (target: any) => boolean = () => false,
managerProperty: string | false = "manager_"
): MethodDecorator {
return function (
target: any,
propertyKey: string | symbol,
descriptor: any
): void {
if (!target.MedusaContextIndex_) {
throw new Error(
`To apply @InjectEntityManager you have to flag a parameter using @MedusaContext`
)
}
const originalMethod = descriptor.value
const argIndex = target.MedusaContextIndex_[propertyKey]
descriptor.value = async function (...args: any[]) {
const shouldForceTransactionRes = shouldForceTransaction(target)
const context: SharedContext | Context = args[argIndex] ?? {}
if (!shouldForceTransactionRes && context?.transactionManager) {
return await originalMethod.apply(this, args)
}
return await (managerProperty === false
? this
: this[managerProperty]
).transaction(
async (transactionManager) => {
args[argIndex] = args[argIndex] ?? { __type: MedusaContextType }
args[argIndex].transactionManager = transactionManager
return await originalMethod.apply(this, args)
},
{
transaction: context?.transactionManager,
isolationLevel: (context as Context)?.isolationLevel,
enableNestedTransactions:
(context as Context).enableNestedTransactions ?? false,
}
)
}
}
}
-1
View File
@@ -5,7 +5,6 @@ export * from "./bundles"
export * from "./common"
export * from "./core-flows"
export * from "./dal"
export * from "./decorators"
export * from "./defaults"
export * from "./dml"
export * from "./event-bus"
@@ -1,4 +1,4 @@
import { Context, SharedContext } from "@medusajs/types"
import { Context } from "@medusajs/types"
import { MedusaContextType } from "./context-parameter"
export function InjectSharedContext(): MethodDecorator {
@@ -17,7 +17,7 @@ export function InjectSharedContext(): MethodDecorator {
const argIndex = target.MedusaContextIndex_[propertyKey]
descriptor.value = function (...args: any[]) {
const context: SharedContext | Context = {
const context: Context = {
...(args[argIndex] ?? { __type: MedusaContextType }),
}
args[argIndex] = context
@@ -1,5 +1,5 @@
import { Context, EventBusTypes } from "@medusajs/types"
import { buildModuleResourceEventName } from "../event-bus"
import { buildModuleResourceEventName } from "../event-bus/utils"
// TODO should that move closer to the event bus? and maybe be rename to modulemoduleEventBuilderFactory
@@ -28,16 +28,11 @@ import { buildModuleResourceEventName } from "../event-bus"
export function moduleEventBuilderFactory({
action,
object,
eventsEnum,
eventName,
source,
}: {
action: string
object: string
/**
* @deprecated use eventName instead
*/
eventsEnum?: Record<string, string>
eventName?: string
source: string
}) {
@@ -57,14 +52,8 @@ export function moduleEventBuilderFactory({
const aggregator = sharedContext.messageAggregator!
const messages: EventBusTypes.RawMessageFormat[] = []
// The event enums contains event formatted like so [object]_[action] e.g. PRODUCT_CREATED
// We expect the keys of events to be fully uppercased
let eventName_ = eventsEnum
? eventsEnum[`${object.toUpperCase()}_${action.toUpperCase()}`]
: eventName
if (!eventName_) {
eventName_ = buildModuleResourceEventName({
if (!eventName) {
eventName = buildModuleResourceEventName({
prefix: source,
objectName: object,
action,
@@ -77,7 +66,7 @@ export function moduleEventBuilderFactory({
action,
context: sharedContext,
data: { id: dataItem.id },
eventName: eventName_,
eventName: eventName!,
object,
})
})
@@ -25,16 +25,6 @@ export type ModelDTOConfig = {
model?: DmlEntity<any, any>
create?: any
update?: any
/**
* @internal
* @deprecated
*/
singular?: string
/**
* @internal
* @deprecated
*/
plural?: string
}
export type ModelsConfigTemplate = { [key: string]: ModelDTOConfig }
@@ -51,21 +41,6 @@ export type ModelConfigurationsToConfigTemplate<T extends ModelEntries> = {
: T[Key] extends IDmlEntity<any, any>
? T[Key]
: never
/**
* @deprecated
*/
create: any
update: any
/**
* @deprecated
*/
singular: T[Key] extends { singular: string } ? T[Key]["singular"] : Key
/**
* @deprecated
*/
plural: T[Key] extends { plural: string }
? T[Key]["plural"]
: Pluralize<Key & string>
}
}
@@ -20,7 +20,7 @@ export const defaultAdminDetailsClaimFields = [
]
export const retrieveTransformQueryConfig = {
defaultFields: defaultAdminDetailsClaimFields,
defaults: defaultAdminDetailsClaimFields,
isList: false,
}
@@ -16,7 +16,7 @@ export const defaultAdminDetailsExchangeFields = [
]
export const retrieveTransformQueryConfig = {
defaultFields: defaultAdminDetailsExchangeFields,
defaults: defaultAdminDetailsExchangeFields,
isList: false,
}
@@ -13,7 +13,7 @@ export const defaultAdminDetailsOrderEditFields = [
]
export const retrieveTransformQueryConfig = {
defaultFields: defaultAdminDetailsOrderEditFields,
defaults: defaultAdminDetailsOrderEditFields,
isList: false,
}
@@ -82,7 +82,7 @@ export const defaultAdminRetrieveOrderChangesFields = [
]
export const retrieveTransformQueryConfig = {
defaultFields: defaultAdminRetrieveOrderFields,
defaults: defaultAdminRetrieveOrderFields,
isList: false,
}
@@ -93,6 +93,6 @@ export const listTransformQueryConfig = {
}
export const retrieveOrderChangesTransformQueryConfig = {
defaultFields: defaultAdminRetrieveOrderChangesFields,
defaults: defaultAdminRetrieveOrderChangesFields,
isList: false,
}
@@ -12,7 +12,7 @@ export const defaultAdminRetrieveRefundReasonFields = [
]
export const retrieveTransformQueryConfig = {
defaultFields: defaultAdminRetrieveRefundReasonFields,
defaults: defaultAdminRetrieveRefundReasonFields,
isList: false,
}
@@ -23,7 +23,7 @@ export const defaultAdminRetrieveReturnReasonFields = [
]
export const retrieveTransformQueryConfig = {
defaultFields: defaultAdminRetrieveReturnReasonFields,
defaults: defaultAdminRetrieveReturnReasonFields,
isList: false,
}
@@ -25,7 +25,7 @@ export const defaultAdminDetailsReturnFields = [
]
export const retrieveTransformQueryConfig = {
defaultFields: defaultAdminDetailsReturnFields,
defaults: defaultAdminDetailsReturnFields,
isList: false,
}
@@ -1,6 +1,6 @@
export const defaultAdminUploadFields = ["id", "url"]
export const retrieveUploadConfig = {
defaultFields: defaultAdminUploadFields,
defaults: defaultAdminUploadFields,
isList: false,
}
@@ -12,7 +12,7 @@ export const defaultStoreRetrieveReturnReasonFields = [
]
export const retrieveTransformQueryConfig = {
defaultFields: defaultStoreRetrieveReturnReasonFields,
defaults: defaultStoreRetrieveReturnReasonFields,
isList: false,
}
@@ -25,22 +25,6 @@ export const BigNumberInput = z.union([
}),
])
const optionalBooleanMapper = new Map([
["undefined", undefined],
["null", null],
["true", true],
["false", false],
])
/**
* @deprecated Use `booleanString` instead
* It support the chainable API of zod. Please note it does not come with `.optional()` by default
*/
export const OptionalBooleanValidator = z.preprocess(
(val: any) => optionalBooleanMapper.get(val?.toLowerCase()),
z.boolean().optional()
)
/**
* Validates that a value is a boolean when it is passed as a string.
*/
+3 -6
View File
@@ -1,8 +1,5 @@
export { default as exec } from "./exec"
export { default as user } from "./user"
export { default as start } from "./start"
export { default as build } from "./build"
export { default as develop } from "./develop"
export { default as exec } from "./exec"
export { default as links } from "./links"
export { default as migrate } from "./migrate"
export { default as start } from "./start"
export { default as startCluster } from "./start-cluster"
export { default as user } from "./user"
-10
View File
@@ -1,10 +0,0 @@
import syncLinksCmd from "./db/sync-links"
const main = async function (argv) {
if (argv.action !== "sync") {
return process.exit()
}
await syncLinksCmd(argv)
}
export default main
-117
View File
@@ -1,117 +0,0 @@
import { LinkLoader } from "@medusajs/framework/links"
import { logger } from "@medusajs/framework/logger"
import { MedusaAppLoader } from "@medusajs/framework"
import { initializeContainer } from "../loaders"
import {
ContainerRegistrationKeys,
MedusaError,
} from "@medusajs/framework/utils"
import { getResolvedPlugins } from "../loaders/helpers/resolve-plugins"
import { join } from "path"
const TERMINAL_SIZE = process.stdout.columns
type Action = "run" | "revert" | "generate" | "show"
function validateInputArgs({
action,
modules,
}: {
action: Action
modules: string[]
}) {
const actionsRequiringModules = ["revert", "generate"]
if (modules.length && !actionsRequiringModules.includes(action)) {
logger.error(
`<modules> cannot be specified with the "${action}" action. Please remove the <modules> argument and try again.`
)
process.exit(1)
}
if (!modules.length && actionsRequiringModules.includes(action)) {
logger.error(
"Please provide the modules for which you want to revert migrations"
)
logger.error(`For example: "npx medusa migration revert <moduleName>"`)
process.exit(1)
}
}
const main = async function ({ directory }) {
const args = process.argv
args.shift()
args.shift()
args.shift()
const action = args[0] as Action
const modules = args.splice(1)
validateInputArgs({ action, modules })
const container = await initializeContainer(directory)
const configModule = container.resolve(
ContainerRegistrationKeys.CONFIG_MODULE
)
const medusaAppLoader = new MedusaAppLoader()
const plugins = getResolvedPlugins(directory, configModule, true) || []
const linksSourcePaths = plugins.map((plugin) =>
join(plugin.resolve, "links")
)
await new LinkLoader(linksSourcePaths).load()
if (action === "run") {
logger.info("Running migrations...")
await medusaAppLoader.runModulesMigrations({
action: "run",
})
console.log(new Array(TERMINAL_SIZE).join("-"))
logger.info("Migrations completed")
process.exit()
} else if (action === "revert") {
logger.info("Reverting migrations...")
try {
await medusaAppLoader.runModulesMigrations({
moduleNames: modules,
action: "revert",
})
console.log(new Array(TERMINAL_SIZE).join("-"))
logger.info("Migrations reverted")
process.exit()
} catch (error) {
console.log(new Array(TERMINAL_SIZE).join("-"))
if (error.code && error.code === MedusaError.Codes.UNKNOWN_MODULES) {
logger.error(error.message)
const modulesList = error.allModules.map(
(name: string) => ` - ${name}`
)
logger.error(`Available modules:\n${modulesList.join("\n")}`)
} else {
logger.error(error.message, error)
}
process.exit(1)
}
} else if (action === "generate") {
logger.info("Generating migrations...")
await medusaAppLoader.runModulesMigrations({
moduleNames: modules,
action: "generate",
})
console.log(new Array(TERMINAL_SIZE).join("-"))
logger.info("Migrations generated")
process.exit()
} else if (action === "show") {
logger.info("Action not supported yet")
process.exit(0)
}
}
export default main
@@ -1,92 +0,0 @@
import cluster from "cluster"
import express from "express"
import { track } from "medusa-telemetry"
import { scheduleJob } from "node-schedule"
import os from "os"
import { logger } from "@medusajs/framework/logger"
import { GracefulShutdownServer, isPresent } from "@medusajs/framework/utils"
import loaders from "../loaders"
const EVERY_SIXTH_HOUR = "0 */6 * * *"
const CRON_SCHEDULE = EVERY_SIXTH_HOUR
let isShuttingDown = false
export default async function ({ port, cpus, directory }) {
if (cluster.isPrimary) {
const killMainProccess = () => process.exit(0)
cpus ??= os.cpus().length
const numCPUs = Math.min(os.cpus().length, cpus)
for (let index = 0; index < numCPUs; index++) {
const worker = cluster.fork()
worker.send({ index })
}
cluster.on("exit", (worker) => {
if (!isShuttingDown) {
cluster.fork()
} else if (!isPresent(cluster.workers)) {
setTimeout(killMainProccess, 100)
}
})
const gracefulShutDown = () => {
isShuttingDown = true
for (const id of Object.keys(cluster.workers ?? {})) {
cluster.workers?.[id]?.kill("SIGTERM")
}
}
scheduleJob(CRON_SCHEDULE, () => {
track("PING")
})
process.on("SIGTERM", gracefulShutDown)
process.on("SIGINT", gracefulShutDown)
} else {
const start = async () => {
track("CLI_START")
const app = express()
const { shutdown } = await loaders({
directory,
expressApp: app,
})
const serverActivity = logger.activity(`Creating server`)
const server = GracefulShutdownServer.create(
app.listen(port).on("listening", () => {
logger.success(serverActivity, `Server is ready on port: ${port}`)
track("CLI_START_COMPLETED")
})
)
const gracefulShutDown = () => {
server
.shutdown()
.then(async () => {
await shutdown()
process.exit(0)
})
.catch((e) => {
process.exit(1)
})
}
process.on("SIGTERM", gracefulShutDown)
process.on("SIGINT", gracefulShutDown)
return { server }
}
process.on("message", async (msg: any) => {
if (msg.index > 0) {
process.env.PLUGIN_ADMIN_UI_SKIP_CACHE = "true"
}
await start()
})
}
}
+62 -6
View File
@@ -1,15 +1,18 @@
import os from "os"
import path from "path"
import http from "http"
import express from "express"
import cluster from "cluster"
import { track } from "medusa-telemetry"
import { scheduleJob } from "node-schedule"
import {
dynamicImport,
isPresent,
FileSystem,
gqlSchemaToTypes,
GracefulShutdownServer,
} from "@medusajs/framework/utils"
import http from "http"
import { logger } from "@medusajs/framework/logger"
import loaders from "../loaders"
@@ -54,8 +57,14 @@ export async function registerInstrumentation(directory: string) {
// eslint-disable-next-line no-var
export var traceRequestHandler: (...args: any[]) => Promise<any> = void 0 as any
async function start({ port, directory, types }) {
async function internalStart() {
async function start(args: {
directory: string
port?: number
types?: boolean
cluster?: number
}) {
const { port, directory, types } = args
async function internalStart(generateTypes: boolean) {
track("CLI_START")
await registerInstrumentation(directory)
@@ -84,7 +93,7 @@ async function start({ port, directory, types }) {
expressApp: app,
})
if (gqlSchema && types) {
if (gqlSchema && generateTypes) {
const outputDirGeneratedTypes = path.join(directory, ".medusa/types")
await gqlSchemaToTypes({
outputDir: outputDirGeneratedTypes,
@@ -93,7 +102,7 @@ async function start({ port, directory, types }) {
schema: gqlSchema,
joinerConfigs: MedusaModule.getAllJoinerConfigs(),
})
logger.info("Geneated modules types")
logger.info("Generated modules types")
}
const serverActivity = logger.activity(`Creating server`)
@@ -133,7 +142,54 @@ async function start({ port, directory, types }) {
}
}
await internalStart()
/**
* When the cluster flag is used we will start the process in
* cluster mode
*/
if ("cluster" in args) {
const maxCpus = os.cpus().length
const cpus = args.cluster ?? maxCpus
if (cluster.isPrimary) {
let isShuttingDown = false
const numCPUs = Math.min(maxCpus, cpus)
const killMainProccess = () => process.exit(0)
const gracefulShutDown = () => {
isShuttingDown = true
for (const id of Object.keys(cluster.workers ?? {})) {
cluster.workers?.[id]?.kill("SIGTERM")
}
}
for (let index = 0; index < numCPUs; index++) {
cluster.fork().send({ index })
}
cluster.on("exit", () => {
if (!isShuttingDown) {
cluster.fork()
} else if (!isPresent(cluster.workers)) {
setTimeout(killMainProccess, 100)
}
})
process.on("SIGTERM", gracefulShutDown)
process.on("SIGINT", gracefulShutDown)
} else {
process.on("message", async (msg: any) => {
if (msg.index > 0) {
process.env.PLUGIN_ADMIN_UI_SKIP_CACHE = "true"
}
await internalStart(!!types && msg.index === 0)
})
}
} else {
/**
* Not in cluster mode
*/
await internalStart(!!types)
}
}
export default start
-6
View File
@@ -40,12 +40,6 @@ declare global {
*/
filterableFields: Record<string, unknown>
includes?: Record<string, boolean>
/**
* An array of fields and relations that are allowed to be queried, this can be set by the
* consumer as part of a middleware and it will take precedence over the defaultAllowedFields
* @deprecated use `allowed` instead
*/
allowedFields?: string[]
/**
* An array of fields and relations that are allowed to be queried, this can be set by the
* consumer as part of a middleware and it will take precedence over the defaultAllowedFields set
@@ -20,151 +20,151 @@ export const eventBuilders = {
source: Modules.FULFILLMENT,
action: CommonEvents.CREATED,
object: "fulfillment",
eventsEnum: FulfillmentEvents,
eventName: FulfillmentEvents.FULFILLMENT_CREATED,
}),
updatedFulfillment: moduleEventBuilderFactory({
source: Modules.FULFILLMENT,
action: CommonEvents.UPDATED,
object: "fulfillment",
eventsEnum: FulfillmentEvents,
eventName: FulfillmentEvents.FULFILLMENT_UPDATED,
}),
createdFulfillmentAddress: moduleEventBuilderFactory({
source: Modules.FULFILLMENT,
action: CommonEvents.CREATED,
object: "fulfillment_address",
eventsEnum: FulfillmentEvents,
eventName: FulfillmentEvents.FULFILLMENT_ADDRESS_CREATED,
}),
createdFulfillmentItem: moduleEventBuilderFactory({
source: Modules.FULFILLMENT,
action: CommonEvents.CREATED,
object: "fulfillment_item",
eventsEnum: FulfillmentEvents,
eventName: FulfillmentEvents.FULFILLMENT_ITEM_CREATED,
}),
createdFulfillmentLabel: moduleEventBuilderFactory({
source: Modules.FULFILLMENT,
action: CommonEvents.CREATED,
object: "fulfillment_label",
eventsEnum: FulfillmentEvents,
eventName: FulfillmentEvents.FULFILLMENT_LABEL_CREATED,
}),
updatedFulfillmentLabel: moduleEventBuilderFactory({
source: Modules.FULFILLMENT,
action: CommonEvents.UPDATED,
object: "fulfillment_label",
eventsEnum: FulfillmentEvents,
eventName: FulfillmentEvents.FULFILLMENT_LABEL_UPDATED,
}),
deletedFulfillmentLabel: moduleEventBuilderFactory({
source: Modules.FULFILLMENT,
action: CommonEvents.DELETED,
object: "fulfillment_label",
eventsEnum: FulfillmentEvents,
eventName: FulfillmentEvents.FULFILLMENT_LABEL_DELETED,
}),
createdShippingProfile: moduleEventBuilderFactory({
source: Modules.FULFILLMENT,
action: CommonEvents.CREATED,
object: "shipping_profile",
eventsEnum: FulfillmentEvents,
eventName: FulfillmentEvents.SHIPPING_PROFILE_CREATED,
}),
createdShippingOptionType: moduleEventBuilderFactory({
source: Modules.FULFILLMENT,
action: CommonEvents.CREATED,
object: "shipping_option_type",
eventsEnum: FulfillmentEvents,
eventName: FulfillmentEvents.SHIPPING_OPTION_TYPE_CREATED,
}),
updatedShippingOptionType: moduleEventBuilderFactory({
source: Modules.FULFILLMENT,
action: CommonEvents.UPDATED,
object: "shipping_option_type",
eventsEnum: FulfillmentEvents,
eventName: FulfillmentEvents.SHIPPING_OPTION_TYPE_UPDATED,
}),
deletedShippingOptionType: moduleEventBuilderFactory({
source: Modules.FULFILLMENT,
action: CommonEvents.DELETED,
object: "shipping_option_type",
eventsEnum: FulfillmentEvents,
eventName: FulfillmentEvents.SHIPPING_OPTION_TYPE_DELETED,
}),
createdShippingOptionRule: moduleEventBuilderFactory({
source: Modules.FULFILLMENT,
action: CommonEvents.CREATED,
object: "shipping_option_rule",
eventsEnum: FulfillmentEvents,
eventName: FulfillmentEvents.SHIPPING_OPTION_RULE_CREATED,
}),
updatedShippingOptionRule: moduleEventBuilderFactory({
source: Modules.FULFILLMENT,
action: CommonEvents.UPDATED,
object: "shipping_option_rule",
eventsEnum: FulfillmentEvents,
eventName: FulfillmentEvents.SHIPPING_OPTION_RULE_UPDATED,
}),
deletedShippingOptionRule: moduleEventBuilderFactory({
source: Modules.FULFILLMENT,
action: CommonEvents.DELETED,
object: "shipping_option_rule",
eventsEnum: FulfillmentEvents,
eventName: FulfillmentEvents.SHIPPING_OPTION_RULE_DELETED,
}),
createdShippingOption: moduleEventBuilderFactory({
source: Modules.FULFILLMENT,
action: CommonEvents.CREATED,
object: "shipping_option",
eventsEnum: FulfillmentEvents,
eventName: FulfillmentEvents.SHIPPING_OPTION_CREATED,
}),
updatedShippingOption: moduleEventBuilderFactory({
source: Modules.FULFILLMENT,
action: CommonEvents.UPDATED,
object: "shipping_option",
eventsEnum: FulfillmentEvents,
eventName: FulfillmentEvents.SHIPPING_OPTION_UPDATED,
}),
createdFulfillmentSet: moduleEventBuilderFactory({
source: Modules.FULFILLMENT,
action: CommonEvents.CREATED,
object: "fulfillment_set",
eventsEnum: FulfillmentEvents,
eventName: FulfillmentEvents.FULFILLMENT_SET_CREATED,
}),
updatedFulfillmentSet: moduleEventBuilderFactory({
source: Modules.FULFILLMENT,
action: CommonEvents.UPDATED,
object: "fulfillment_set",
eventsEnum: FulfillmentEvents,
eventName: FulfillmentEvents.FULFILLMENT_SET_UPDATED,
}),
deletedFulfillmentSet: moduleEventBuilderFactory({
source: Modules.FULFILLMENT,
action: CommonEvents.DELETED,
object: "fulfillment_set",
eventsEnum: FulfillmentEvents,
eventName: FulfillmentEvents.FULFILLMENT_SET_DELETED,
}),
createdServiceZone: moduleEventBuilderFactory({
source: Modules.FULFILLMENT,
action: CommonEvents.CREATED,
object: "service_zone",
eventsEnum: FulfillmentEvents,
eventName: FulfillmentEvents.SERVICE_ZONE_CREATED,
}),
updatedServiceZone: moduleEventBuilderFactory({
source: Modules.FULFILLMENT,
action: CommonEvents.UPDATED,
object: "service_zone",
eventsEnum: FulfillmentEvents,
eventName: FulfillmentEvents.SERVICE_ZONE_UPDATED,
}),
deletedServiceZone: moduleEventBuilderFactory({
source: Modules.FULFILLMENT,
action: CommonEvents.DELETED,
object: "service_zone",
eventsEnum: FulfillmentEvents,
eventName: FulfillmentEvents.SERVICE_ZONE_DELETED,
}),
createdGeoZone: moduleEventBuilderFactory({
source: Modules.FULFILLMENT,
action: CommonEvents.CREATED,
object: "geo_zone",
eventsEnum: FulfillmentEvents,
eventName: FulfillmentEvents.GEO_ZONE_CREATED,
}),
updatedGeoZone: moduleEventBuilderFactory({
source: Modules.FULFILLMENT,
action: CommonEvents.UPDATED,
object: "geo_zone",
eventsEnum: FulfillmentEvents,
eventName: FulfillmentEvents.GEO_ZONE_UPDATED,
}),
deletedGeoZone: moduleEventBuilderFactory({
source: Modules.FULFILLMENT,
action: CommonEvents.DELETED,
object: "geo_zone",
eventsEnum: FulfillmentEvents,
eventName: FulfillmentEvents.GEO_ZONE_DELETED,
}),
}
@@ -10,6 +10,6 @@ export const eventBuilders = {
source: Modules.NOTIFICATION,
action: CommonEvents.CREATED,
object: "notification",
eventsEnum: NotificationEvents,
eventName: NotificationEvents.NOTIFICATION_CREATED,
}),
}
+10 -10
View File
@@ -10,60 +10,60 @@ export const eventBuilders = {
source: Modules.PRICING,
action: CommonEvents.CREATED,
object: "price_set",
eventsEnum: PricingEvents,
eventName: PricingEvents.PRICE_SET_CREATED,
}),
createdPrice: moduleEventBuilderFactory({
source: Modules.PRICING,
action: CommonEvents.CREATED,
object: "price",
eventsEnum: PricingEvents,
eventName: PricingEvents.PRICE_CREATED,
}),
createdPriceRule: moduleEventBuilderFactory({
source: Modules.PRICING,
action: CommonEvents.CREATED,
object: "price_rule",
eventsEnum: PricingEvents,
eventName: PricingEvents.PRICE_RULE_CREATED,
}),
createdPriceList: moduleEventBuilderFactory({
source: Modules.PRICING,
action: CommonEvents.CREATED,
object: "price_list",
eventsEnum: PricingEvents,
eventName: PricingEvents.PRICE_LIST_CREATED,
}),
createdPriceListRule: moduleEventBuilderFactory({
source: Modules.PRICING,
action: CommonEvents.CREATED,
object: "price_list_rule",
eventsEnum: PricingEvents,
eventName: PricingEvents.PRICE_LIST_RULE_CREATED,
}),
attachedPriceListRule: moduleEventBuilderFactory({
source: Modules.PRICING,
action: CommonEvents.ATTACHED,
object: "price_list_rule",
eventsEnum: PricingEvents,
eventName: PricingEvents.PRICE_LIST_RULE_ATTACHED,
}),
updatedPrice: moduleEventBuilderFactory({
source: Modules.PRICING,
action: CommonEvents.UPDATED,
object: "price",
eventsEnum: PricingEvents,
eventName: PricingEvents.PRICE_UPDATED,
}),
updatedPriceRule: moduleEventBuilderFactory({
source: Modules.PRICING,
action: CommonEvents.UPDATED,
object: "price_rule",
eventsEnum: PricingEvents,
eventName: PricingEvents.PRICE_RULE_UPDATED,
}),
deletedPrice: moduleEventBuilderFactory({
source: Modules.PRICING,
action: CommonEvents.DELETED,
object: "price",
eventsEnum: PricingEvents,
eventName: PricingEvents.PRICE_DELETED,
}),
deletedPriceRule: moduleEventBuilderFactory({
source: Modules.PRICING,
action: CommonEvents.DELETED,
object: "price_rule",
eventsEnum: PricingEvents,
eventName: PricingEvents.PRICE_RULE_DELETED,
}),
}
@@ -680,7 +680,6 @@ moduleIntegrationTestRunner<IProductModuleService>({
productCategoryTwo = categories[2]
})
// TODO: Normalize delete events as well
it("should emit events through event bus", async () => {
const eventBusSpy = jest.spyOn(MockEventBusService.prototype, "emit")
eventBusSpy.mockClear()
+18 -18
View File
@@ -10,109 +10,109 @@ export const eventBuilders = {
source: Modules.PRODUCT,
action: CommonEvents.CREATED,
object: "product",
eventsEnum: ProductEvents,
eventName: ProductEvents.PRODUCT_CREATED,
}),
updatedProduct: moduleEventBuilderFactory({
source: Modules.PRODUCT,
action: CommonEvents.UPDATED,
object: "product",
eventsEnum: ProductEvents,
eventName: ProductEvents.PRODUCT_UPDATED,
}),
deletedProduct: moduleEventBuilderFactory({
source: Modules.PRODUCT,
action: CommonEvents.DELETED,
object: "product",
eventsEnum: ProductEvents,
eventName: ProductEvents.PRODUCT_DELETED,
}),
createdProductVariant: moduleEventBuilderFactory({
source: Modules.PRODUCT,
action: CommonEvents.CREATED,
object: "product_variant",
eventsEnum: ProductEvents,
eventName: ProductEvents.PRODUCT_VARIANT_CREATED,
}),
updatedProductVariant: moduleEventBuilderFactory({
source: Modules.PRODUCT,
action: CommonEvents.UPDATED,
object: "product_variant",
eventsEnum: ProductEvents,
eventName: ProductEvents.PRODUCT_VARIANT_UPDATED,
}),
deletedProductVariant: moduleEventBuilderFactory({
source: Modules.PRODUCT,
action: CommonEvents.DELETED,
object: "product_variant",
eventsEnum: ProductEvents,
eventName: ProductEvents.PRODUCT_VARIANT_DELETED,
}),
createdProductOption: moduleEventBuilderFactory({
source: Modules.PRODUCT,
action: CommonEvents.CREATED,
object: "product_option",
eventsEnum: ProductEvents,
eventName: ProductEvents.PRODUCT_OPTION_CREATED,
}),
updatedProductOption: moduleEventBuilderFactory({
source: Modules.PRODUCT,
action: CommonEvents.UPDATED,
object: "product_option",
eventsEnum: ProductEvents,
eventName: ProductEvents.PRODUCT_OPTION_UPDATED,
}),
deletedProductOption: moduleEventBuilderFactory({
source: Modules.PRODUCT,
action: CommonEvents.DELETED,
object: "product_option",
eventsEnum: ProductEvents,
eventName: ProductEvents.PRODUCT_OPTION_DELETED,
}),
createdProductType: moduleEventBuilderFactory({
source: Modules.PRODUCT,
action: CommonEvents.CREATED,
object: "product_type",
eventsEnum: ProductEvents,
eventName: ProductEvents.PRODUCT_TYPE_CREATED,
}),
updatedProductType: moduleEventBuilderFactory({
source: Modules.PRODUCT,
action: CommonEvents.UPDATED,
object: "product_type",
eventsEnum: ProductEvents,
eventName: ProductEvents.PRODUCT_TYPE_UPDATED,
}),
deletedProductType: moduleEventBuilderFactory({
source: Modules.PRODUCT,
action: CommonEvents.DELETED,
object: "product_type",
eventsEnum: ProductEvents,
eventName: ProductEvents.PRODUCT_TYPE_DELETED,
}),
createdProductTag: moduleEventBuilderFactory({
source: Modules.PRODUCT,
action: CommonEvents.CREATED,
object: "product_tag",
eventsEnum: ProductEvents,
eventName: ProductEvents.PRODUCT_TAG_CREATED,
}),
updatedProductTag: moduleEventBuilderFactory({
source: Modules.PRODUCT,
action: CommonEvents.UPDATED,
object: "product_tag",
eventsEnum: ProductEvents,
eventName: ProductEvents.PRODUCT_TAG_UPDATED,
}),
deletedProductTag: moduleEventBuilderFactory({
source: Modules.PRODUCT,
action: CommonEvents.DELETED,
object: "product_tag",
eventsEnum: ProductEvents,
eventName: ProductEvents.PRODUCT_TAG_DELETED,
}),
createdProductCategory: moduleEventBuilderFactory({
source: Modules.PRODUCT,
action: CommonEvents.CREATED,
object: "product_category",
eventsEnum: ProductEvents,
eventName: ProductEvents.PRODUCT_CATEGORY_CREATED,
}),
updatedProductCategory: moduleEventBuilderFactory({
source: Modules.PRODUCT,
action: CommonEvents.UPDATED,
object: "product_category",
eventsEnum: ProductEvents,
eventName: ProductEvents.PRODUCT_CATEGORY_UPDATED,
}),
deletedProductCategory: moduleEventBuilderFactory({
source: Modules.PRODUCT,
action: CommonEvents.DELETED,
object: "product_category",
eventsEnum: ProductEvents,
eventName: ProductEvents.PRODUCT_CATEGORY_DELETED,
}),
createdProductCollection: moduleEventBuilderFactory({
source: Modules.PRODUCT,