chore: More cleanup of medusa package (#7332)

This commit is contained in:
Stevche Radevski authored and GitHub committed 2024-05-15 09:42:06 +02:00
1 parent 70fd355e46
commit 5c14d283d0
28 files changed
+12 -463

No files matched your search

@@ -1,9 +0,0 @@
module.exports = {
featureFlags: {},
projectConfig: {
database_url: "postgres://localhost/medusa-store",
database_logging: false
},
plugins: [],
modules: {},
};
@@ -1,11 +0,0 @@
import { Column, Entity } from "typeorm"
import {
// alias the core entity to not cause a naming conflict
Product as MedusaProduct,
} from "@medusajs/medusa"
@Entity()
export class Product extends MedusaProduct {
@Column()
custom_attribute: string = 'test'
}
+1 -1
View File
@@ -3,8 +3,8 @@ import { AwilixContainer } from "awilix"
import { Express } from "express"
import path from "path"
import qs from "qs"
import { ConfigModule } from "../types/global"
import { RoutesLoader } from "./helpers/routing"
import { ConfigModule } from "@medusajs/types"
type Options = {
app: Express
+1 -1
View File
@@ -1,6 +1,6 @@
import { getConfigFile, isDefined } from "medusa-core-utils"
import { ConfigModule } from "../types/global"
import logger from "./logger"
import { ConfigModule } from "@medusajs/types"
const isProduction = ["production", "prod"].includes(process.env.NODE_ENV || "")
-71
View File
@@ -1,71 +0,0 @@
import { handlePostgresDatabaseError } from "@medusajs/utils"
import { AwilixContainer } from "awilix"
import {
DataSource,
DataSourceOptions,
Repository,
TreeRepository,
} from "typeorm"
import { ConfigModule } from "../types/global"
type Options = {
configModule: ConfigModule
container: AwilixContainer
customOptions?: {
migrations: DataSourceOptions["migrations"]
logging: DataSourceOptions["logging"]
}
}
export let dataSource: DataSource
// TODO: With the latest version of typeorm, the datasource is expected to be
// available globally. During the integration test, the medusa
// files are imported from @medusajs/medusa, therefore, the repositories are
// evaluated at the same time, unfortunately, the integration tests have their
// own way to load and at the moment, the datasource does not exists. This is
// why we are mocking them here
if (process.env.NODE_ENV === "test") {
dataSource = {
getRepository: (target) => new Repository(target, {} as any) as any,
getTreeRepository: (target) => new TreeRepository(target, {} as any) as any,
} as unknown as DataSource
}
export default async ({
container,
configModule,
customOptions,
}: Options): Promise<DataSource> => {
const entities = container.resolve("db_entities")
const connectionString = configModule.projectConfig.database_url
const database = configModule.projectConfig.database_database
const extra: any = configModule.projectConfig.database_extra || {}
const schema = configModule.projectConfig.database_schema || "public"
dataSource = new DataSource({
type: "postgres",
url: connectionString,
database: database,
extra,
schema,
entities,
migrations: customOptions?.migrations,
logging:
customOptions?.logging ??
(configModule.projectConfig.database_logging || false),
} as DataSourceOptions)
await dataSource.initialize().catch(handlePostgresDatabaseError)
// If migrations are not included in the config, we assume you are attempting to start the server
// Therefore, throw if the database is not migrated
if (!dataSource.migrations?.length) {
await dataSource
.query(`select * from migrations`)
.catch(handlePostgresDatabaseError)
}
return dataSource
}
+1 -1
View File
@@ -4,7 +4,7 @@ import { Express } from "express"
import session from "express-session"
import morgan from "morgan"
import Redis from "ioredis"
import { ConfigModule } from "../types/global"
import { ConfigModule } from "@medusajs/types"
type Options = {
app: Express
@@ -1,58 +0,0 @@
import glob from "glob"
import path from "path"
import { EntitySchema } from "typeorm"
import { formatRegistrationName } from "../../utils/format-registration-name"
import { ClassConstructor } from "../../types/global"
type GetModelExtensionMapParams = {
directory?: string
pathGlob?: string
config: Record<string, any>
}
export function getModelExtensionsMap({
directory,
pathGlob,
config = {},
}: GetModelExtensionMapParams): Map<
string,
ClassConstructor<unknown> | EntitySchema
> {
const modelExtensionsMap = new Map<
string,
ClassConstructor<unknown> | EntitySchema
>()
const fullPathGlob =
directory && pathGlob ? path.join(directory, pathGlob) : null
const modelExtensions = fullPathGlob
? glob.sync(fullPathGlob, {
cwd: directory,
ignore: ["index.js", "index.js.map"],
})
: []
modelExtensions.forEach((modelExtensionPath) => {
const extendedModel = require(modelExtensionPath) as
| ClassConstructor<unknown>
| EntitySchema
| undefined
if (extendedModel) {
Object.entries(extendedModel).map(
([_key, val]: [string, ClassConstructor<unknown> | EntitySchema]) => {
if (typeof val === "function" || val instanceof EntitySchema) {
if (config.register) {
const name = formatRegistrationName(modelExtensionPath)
modelExtensionsMap.set(name, val)
}
}
}
)
}
})
return modelExtensionsMap
}
@@ -10,7 +10,6 @@ import {
errorHandler,
requireCustomerAuthentication,
} from "../../../utils/middlewares"
import { ConfigModule } from "../../../types/global"
import { MedusaRequest, MedusaResponse } from "../../../types/routing"
import logger from "../../logger"
import {
@@ -25,6 +24,7 @@ import {
RouteDescriptor,
RouteVerb,
} from "./types"
import { ConfigModule } from "@medusajs/types"
const log = ({
activityId,
@@ -4,11 +4,12 @@ import glob from "glob"
import { trackInstallation } from "medusa-telemetry"
import { EOL } from "os"
import path from "path"
import { ConfigModule, Logger, MedusaContainer } from "../types/global"
import { Logger, MedusaContainer } from "../types/global"
import { getResolvedPlugins } from "./helpers/resolve-plugins"
import { RoutesLoader } from "./helpers/routing"
import { SubscriberLoader } from "./helpers/subscribers"
import logger from "./logger"
import { ConfigModule } from "@medusajs/types"
type Options = {
rootDirectory: string
+1 -1
View File
@@ -1,9 +1,9 @@
import { ConfigModule } from "@medusajs/types"
import { Express } from "express"
import passport from "passport"
import { Strategy as CustomStrategy } from "passport-custom"
import { ExtractJwt, Strategy as JWTStrategy } from "passport-jwt"
/* import { AuthService } from "../services"*/
import { ConfigModule } from "../types/global"
export default async ({
app,
+1 -1
View File
@@ -1,6 +1,6 @@
import { ConfigModule } from "@medusajs/types"
import { ContainerRegistrationKeys, ModulesSdkUtils } from "@medusajs/utils"
import { asValue, AwilixContainer } from "awilix"
import { ConfigModule } from "../types/global"
type Options = {
configModule: ConfigModule
+2 -1
View File
@@ -2,7 +2,8 @@ import { asValue } from "awilix"
import Redis from "ioredis"
import FakeRedis from "ioredis-mock"
import { EOL } from "os"
import { ConfigModule, Logger, MedusaContainer } from "../types/global"
import { Logger, MedusaContainer } from "../types/global"
import { ConfigModule } from "@medusajs/types"
type Options = {
container: MedusaContainer
-120
View File
@@ -1,35 +1,4 @@
import "reflect-metadata"
import {
FindManyOptions,
FindOneOptions,
FindOperator,
FindOptionsSelect,
FindOptionsWhere,
OrderByCondition,
} from "typeorm"
import { FindOptionsOrder } from "typeorm/find-options/FindOptionsOrder"
import { FindOptionsRelations } from "typeorm/find-options/FindOptionsRelations"
/**
* Utility type used to remove some optional attributes (coming from K) from a type T
*/
export type WithRequiredProperty<T, K extends keyof T> = T & {
// -? removes 'optional' from a property
[Property in K]-?: T[Property]
}
export type PartialPick<T, K extends keyof T> = {
[P in K]?: T[P]
}
export type Writable<T> = {
-readonly [key in keyof T]:
| T[key]
| FindOperator<T[key]>
| FindOperator<T[key][]>
| FindOperator<string[]>
}
export interface FindConfig<Entity> {
select?: (keyof Entity)[]
@@ -39,55 +8,6 @@ export interface FindConfig<Entity> {
order?: { [K: string]: "ASC" | "DESC" }
}
export type ExtendedFindConfig<TEntity> = (
| Omit<FindOneOptions<TEntity>, "where" | "relations" | "select">
| Omit<FindManyOptions<TEntity>, "where" | "relations" | "select">
) & {
select?: FindOptionsSelect<TEntity>
relations?: FindOptionsRelations<TEntity>
where: FindOptionsWhere<TEntity> | FindOptionsWhere<TEntity>[]
order?: FindOptionsOrder<TEntity>
skip?: number
take?: number
}
export type QuerySelector<TEntity> = Selector<TEntity> & { q?: string }
export type TreeQuerySelector<TEntity> = QuerySelector<TEntity> & {
include_descendants_tree?: boolean
}
type InnerSelector<TEntity> = {
[key in keyof TEntity]?:
| TEntity[key]
| TEntity[key][]
| FindOperator<TEntity[key][] | string | string[]>
}
export type Selector<TEntity> =
| InnerSelector<TEntity>
| InnerSelector<TEntity>[]
export type TotalField =
| "shipping_total"
| "discount_total"
| "tax_total"
| "refunded_total"
| "total"
| "subtotal"
| "refundable_amount"
| "gift_card_total"
| "gift_card_tax_total"
export interface CustomFindOptions<TModel, InKeys extends keyof TModel> {
select?: FindManyOptions<TModel>["select"]
where?: FindManyOptions<TModel>["where"] & {
[P in InKeys]?: TModel[P][]
}
order?: OrderByCondition
skip?: number
take?: number
}
export type QueryConfig<TEntity> = {
/**
* Default fields and relations to return
@@ -116,43 +36,3 @@ export type QueryConfig<TEntity> = {
defaultLimit?: number
isList?: boolean
}
/**
* @interface
*
* Pagination fields returned in the response of an API route.
*/
export type PaginatedResponse = {
/**
* The maximum number of items that can be returned in the list.
*/
limit: number
/**
* The number of items skipped before the returned items in the list.
*/
offset: number
/**
* The total number of items available.
*/
count: number
}
/**
* @interface
*
* The response returned for a `DELETE` request.
*/
export type DeleteResponse = {
/**
* The ID of the deleted item.
*/
id: string
/**
* The type of the deleted item.
*/
object: string
/**
* Whether the item was deleted successfully.
*/
deleted: boolean
}
+1 -6
View File
@@ -1,5 +1,4 @@
import { CommonTypes, RequestQueryFields } from "@medusajs/types"
import { Request } from "express"
import { RequestQueryFields } from "@medusajs/types"
import { MedusaContainer as coreMedusaContainer } from "medusa-core-utils"
import { FindConfig } from "./common"
@@ -57,8 +56,6 @@ declare global {
}
}
export type ExtendedRequest<TEntity> = Request & { resource: TEntity }
export type ClassConstructor<T> = {
new (...args: unknown[]): T
}
@@ -82,5 +79,3 @@ export type Logger = {
}
export type Constructor<T> = new (...args: any[]) => T
export type ConfigModule = CommonTypes.ConfigModule
-3
View File
@@ -1,3 +0,0 @@
export type RequestContext = {
ip: string
}
-11
View File
@@ -1,11 +0,0 @@
import { isDate } from "lodash"
export const isPast = (date: Date | null) => {
const now = new Date()
return isDate(date) && now > date
}
export const isFuture = (date: Date | null) => {
const now = new Date()
return isDate(date) && date > now
}
-4
View File
@@ -1,10 +1,6 @@
export * from "./clean-response-data"
export * from "./exception-formatter"
export * from "./is-date"
export * from "./is-object"
export * from "./is-string"
export * from "./omit-deep"
export * from "./remote-query-fetch-data"
export * from "./remove-undefined-properties"
export * from "./set-metadata"
export * from "./middlewares"
-4
View File
@@ -1,4 +0,0 @@
export function isDate(value: any): value is Date {
const date = new Date(value)
return !isNaN(date.valueOf())
}
-3
View File
@@ -1,3 +0,0 @@
export function isObject(obj: any): obj is object {
return obj != null && obj?.constructor?.name === "Object"
}
-3
View File
@@ -1,3 +0,0 @@
export function isString(val: any): val is string {
return val != null && typeof val === "string"
}
@@ -1,29 +0,0 @@
import { ConfigModule } from "@medusajs/types"
/**
* Merge the modules config from the medusa-config file with the modules config from medusa package
* @param modules
* @param medusaInternalModulesConfig
*/
export function mergeModulesConfig(
modules: ConfigModule["modules"] = {},
medusaInternalModulesConfig = {}
) {
const modules_ = ({ ...modules } as ConfigModule["modules"])!
const userModulesConfigKeys = Object.keys(modules)
const internalModulesConfigKeys = Object.keys(medusaInternalModulesConfig)
const allModulesKeys = new Set([
...userModulesConfigKeys,
...internalModulesConfigKeys,
])
for (const moduleName of allModulesKeys) {
const internalModuleConfig = medusaInternalModulesConfig[moduleName]
modules_[moduleName] ??= internalModuleConfig
}
return modules_
}
@@ -1,39 +0,0 @@
import { NextFunction, Request, RequestHandler, Response } from "express"
type handler = (req: Request, res: Response) => Promise<void>
/**
* @deprecated use `import { wrapHandler } from "@medusajs/utils"`
*/
export default (fn: handler): RequestHandler => {
return async (req: Request, res: Response, next: NextFunction) => {
if (req?.errors?.length) {
return res.status(400).json({
errors: req.errors,
message:
"Provided request body contains errors. Please check the data and retry the request",
})
}
try {
return await fn(req, res)
} catch (err) {
next(err)
}
}
}
/**
* @schema MultipleErrors
* title: "Multiple Errors"
* type: object
* properties:
* errors:
* type: array
* description: Array of errors
* items:
* $ref: "#/components/schemas/Error"
* message:
* type: string
* default: "Provided request body contains errors. Please check the data and retry the request"
*/
@@ -1,15 +0,0 @@
import { NextFunction, Request, Response } from "express"
export function checkRegisteredModules(services: {
[serviceName: string]: string
}): (req: Request, res: Response, next: NextFunction) => Promise<void> {
return async (req: Request, res: Response, next: NextFunction) => {
for (const service of Object.keys(services)) {
if (!req.scope.resolve(service, { allowUnregistered: true })) {
return next(new Error(services[service]))
}
}
next()
}
}
@@ -1,18 +0,0 @@
import { FlagRouter } from "@medusajs/utils"
import { NextFunction, Request, Response } from "express"
export function isFeatureFlagEnabled(
flagKey: string
): (req: Request, res: Response, next: NextFunction) => Promise<void> {
return async (req: Request, res: Response, next: NextFunction) => {
const featureFlagRouter = req.scope.resolve(
"featureFlagRouter"
) as FlagRouter
if (!featureFlagRouter.isFeatureEnabled(flagKey)) {
res.sendStatus(404)
} else {
next()
}
}
}
@@ -1,7 +1,5 @@
export { default as authenticateLegacy } from "./authenticate"
export { authenticate } from "./authenticate-middleware"
export { default as authenticateCustomer } from "./authenticate-customer"
export { default as wrapHandler } from "./await-middleware"
export { default as errorHandler } from "./error-handler"
export { isFeatureFlagEnabled } from "./feature-flag-enabled"
export { default as requireCustomerAuthentication } from "./require-customer-authentication"
+1 -1
View File
@@ -1,4 +1,4 @@
import { isObject } from "./is-object"
import { isObject } from "@medusajs/utils"
export function omitDeep<T extends object = object>(
input: object,
-45
View File
@@ -1,45 +0,0 @@
import { MedusaError } from "medusa-core-utils/dist"
/**
* Dedicated method to set metadata.
* @param metadata - the metadata to set
* @param obj - the entity to apply metadata to.
* @return resolves to the updated result.
*/
export function setMetadata(
obj: { metadata: Record<string, unknown> | null } | null | undefined,
metadata: Record<string, unknown>
): Record<string, unknown> {
const existing = obj?.metadata || {}
const newData = {}
for (const [key, value] of Object.entries(metadata)) {
if (typeof key !== "string") {
throw new MedusaError(
MedusaError.Types.INVALID_ARGUMENT,
"Key type is invalid. Metadata keys must be strings"
)
}
/**
* We reserve the empty string as a way to delete a key.
* If the value is an empty string, we don't
* set it, and if it exists in the existing metadata, we
* unset the field.
*/
if (value === "") {
if (key in existing) {
delete existing[key]
}
continue
}
newData[key] = value
}
return {
...existing,
...newData,
}
}
-3
View File
@@ -1,3 +0,0 @@
import { promisify } from "util"
export const sleep = promisify(setTimeout)