Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add support for medusa 1.8 @next #181

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.lint.json',
project: `${__dirname}/tsconfig.lint.json`,
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin', "prettier"],
Expand Down
3,599 changes: 2,371 additions & 1,228 deletions package-lock.json

Large diffs are not rendered by default.

12 changes: 6 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -71,21 +71,21 @@
"webpack": "^5.0.0"
},
"peerDependencies": {
"@medusajs/medusa": "^1.7.2",
"@medusajs/medusa": "^1.8.0-next-20230226124736",
"awilix": "^8.0.0",
"express": "^4.17.2",
"medusa-core-utils": "1.x",
"medusa-interfaces": "1.x",
"medusa-interfaces": "1.3.7-snapshot-20230215145050",
"reflect-metadata": "^0.1.13",
"typeorm": "^0.2.41"
"typeorm": "^0.3.11"
},
"devDependencies": {
"@appnest/readme": "^1.2.7",
"@commitlint/cli": "^16.1.0",
"@commitlint/config-angular": "^16.0.0",
"@commitlint/config-conventional": "^16.0.0",
"@commitlint/prompt-cli": "^16.1.0",
"@medusajs/medusa": "^1.7.2",
"@medusajs/medusa": "^1.8.0-next-20230226124736",
"@types/express": "^4.17.13",
"@types/jest": "^27.4.0",
"@types/node": "^17.0.15",
Expand All @@ -104,7 +104,7 @@
"jest": "^27.5.0",
"jest-coverage-badges": "^1.1.2",
"medusa-core-utils": "1.x",
"medusa-interfaces": "1.x",
"medusa-interfaces": "1.3.7-snapshot-20230215145050",
"mongoose": "^6.2.1",
"prettier": "^2.5.1",
"prom-client": "^12.0.0",
Expand All @@ -120,7 +120,7 @@
"typedoc": "^0.23.23",
"typedoc-plugin-markdown": "^3.11.13",
"typedoc-plugin-missing-exports": "^0.23.0",
"typeorm": "^0.2.41",
"typeorm": "^0.3.11",
"typescript": "^4.5.5"
}
}
27 changes: 25 additions & 2 deletions src/Medusa.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,33 @@ import {
databaseLoader,
modulesLoader,
overrideEntitiesLoader,
overrideRepositoriesLoader,
pluginsLoadersProvidersAndListeners,
repositoryLoader,
servicesLoader,
storeApiLoader,
subscribersLoader,
validatorsLoader,
} from './loaders';
import { Repository, TreeRepository } from 'typeorm';

import { Module } from 'module';
const originalRequire = Module.prototype.require;

Module.prototype.require = new Proxy(Module.prototype.require, {
apply(target, thisArg, argumentsList) {
const name = argumentsList[0];

const module = Reflect.apply(target, thisArg, argumentsList);
if (/.*database.*/g.test(name)) {
(module as any).dataSource = {
getRepository: (target) => new Repository(target, {} as any),
getTreeRepository: (target) => new TreeRepository(target, {} as any),
};
}

return module;
},
});

// Use to fix MiddlewareService typings
declare global {
Expand Down Expand Up @@ -46,9 +66,10 @@ export class Medusa {
public async load(modules: Type[]): Promise<MedusaContainer> {
const configModule = await asyncLoadConfig(this.#rootDir, 'medusa-config');
const moduleComponentsOptions = await modulesLoader(modules, configModule);

await validatorsLoader(moduleComponentsOptions.get('validator') ?? []);
await overrideEntitiesLoader(moduleComponentsOptions.get('entity') ?? []);
await overrideRepositoriesLoader(moduleComponentsOptions.get('repository') ?? []);
await repositoryLoader(moduleComponentsOptions.get('repository') ?? []);
await customApiLoader(
this.#express,
moduleComponentsOptions.get('middleware') ?? [],
Expand All @@ -64,6 +85,7 @@ export class Medusa {
moduleComponentsOptions.get('middleware') ?? [],
moduleComponentsOptions.get('router') ?? []
);

await databaseLoader(
moduleComponentsOptions.get('entity') ?? [],
moduleComponentsOptions.get('repository') ?? [],
Expand All @@ -87,6 +109,7 @@ export class Medusa {
}
logger.flush();

Module.prototype.require = originalRequire;
return container as any;
}
}
7 changes: 4 additions & 3 deletions src/core/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,13 @@ export type ServiceInjectableOptions<TOverride = unknown> = {
/**
* Defines the injection options for services, entities, repositories.
*/
export type RepositoryInjectableOptions<TOverride = unknown> = {
export type RepositoryInjectableOptions = {
/**
* @deprecated since v1.6.1
*/
resolutionKey?: string;
override?: Type<TOverride>;
override?: any;
repository: any;
};

/**
Expand Down Expand Up @@ -115,7 +116,7 @@ export type ModuleInjectionOptions<T = unknown> = {
export type InjectableOptions<T = unknown> =
| EntityInjectableOptions<T>
| ServiceInjectableOptions<T>
| RepositoryInjectableOptions<T>
| RepositoryInjectableOptions
| MiddlewareInjectionOptions
| RouterInjectionOptions
| ValidatorInjectionOptions<T>;
Expand Down
2 changes: 1 addition & 1 deletion src/core/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export function attachOrReplaceEntitySubscriber<T extends Constructor<EntitySubs
* @param keys
* @constructor
*/
export const Omit = <T, K extends keyof T>(Class: new () => T, keys: K[]): new () => Omit<T, typeof keys[number]> =>
export const Omit = <T, K extends keyof T>(Class: new () => T, keys: K[]): new () => Omit<T, (typeof keys)[number]> =>
Class;

/**
Expand Down
2 changes: 1 addition & 1 deletion src/decorators/components.decorator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export function Service<T = unknown>(options: ServiceInjectableOptions<T> = {}):
* @param options
* @constructor
*/
export function Repository<T = unknown>(options: RepositoryInjectableOptions<T> = {}): ClassDecorator {
export function Repository(options: RepositoryInjectableOptions = {} as RepositoryInjectableOptions): ClassDecorator {
return buildComponentDecorator({ type: 'repository', ...options });
}

Expand Down
5 changes: 3 additions & 2 deletions src/decorators/tests/components.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import 'reflect-metadata';
import { Repository as EntityRepository } from 'typeorm';
import { Entity, Middleware, Migration, Repository, Router, Service, Validator } from '../components.decorator';
import { INJECTABLE_OPTIONS_KEY } from '../../core';

Expand All @@ -25,11 +26,11 @@ describe('components', () => {

describe('Repository', () => {
it('should define the repository metadata', () => {
@Repository()
@Repository({ repository: new EntityRepository() })
class Test {}

const metadata = Reflect.getMetadata(INJECTABLE_OPTIONS_KEY, Test);
expect(metadata).toEqual({ type: 'repository' });
expect(metadata).toEqual({ type: 'repository', repository: new EntityRepository() });
});
});

Expand Down
30 changes: 28 additions & 2 deletions src/loaders/database.loader.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { repositoriesLoader } from './repository.loader';
import { entitiesLoader } from './entities.loader';
import { GetInjectableOptions, migrationsLoader } from './';
import { MedusaContainer } from '@medusajs/medusa/dist/types/global';
Expand All @@ -12,9 +11,36 @@ export async function databaseLoader(
const originalDatabaseLoader = databaseLoader.default;
databaseLoader.default = async ({ container, configModule }) => {
await entitiesLoader(entities, container as unknown as MedusaContainer);
await repositoriesLoader(repositories, container as unknown as MedusaContainer);

const loadedRepositories = Object.keys(require.cache).filter((f) => {
return (
((f.includes('database') || f.includes('repositories')) && !f.includes('loaders')) ||
(f.includes('repository') && !f.includes('node_modules'))
);
});
loadedRepositories.forEach((key) => {
delete require.cache[key];
});

const connection = await originalDatabaseLoader({ container, configModule });

const Module = await import('module');

Module.prototype.require = new Proxy(Module.prototype.require, {
apply(target, thisArg, argumentsList) {
const name = argumentsList[0];

const module = Reflect.apply(target, thisArg, argumentsList);
if (/.*database.*/g.test(name)) {
(module as any).dataSource = connection;
}

return module;
},
});

await migrationsLoader(migrations, connection);

return connection;
};
}
43 changes: 25 additions & 18 deletions src/loaders/repository.loader.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
import { GetInjectableOption, GetInjectableOptions, lowerCaseFirst } from './';
import { MedusaContainer } from '@medusajs/medusa/dist/types/global';
import { asClass } from 'awilix';
import { getMetadataArgsStorage } from 'typeorm';
import { asClass, asValue } from 'awilix';
import { Logger } from '../core';

const logger = Logger.contextualize('RepositoriesLoader');

export async function repositoryLoader(repositories: GetInjectableOptions<'repository'>): Promise<void> {
const repoLoader = await import('@medusajs/medusa/dist/loaders/repositories');
const originalRepoLoader = repoLoader.default;
repoLoader.default = ({ container }) => {
originalRepoLoader({ container });
repositoriesLoader(repositories, container as unknown as MedusaContainer);
overrideRepositoriesLoader(repositories, container as unknown as MedusaContainer);
};
}

/**
* @internal
* Load all custom repositories into the underlying @medusajs instance.
Expand Down Expand Up @@ -35,13 +44,16 @@ export async function repositoriesLoader(
* Load all custom repositories that override @medusajs instance entities.
* @param repositories
*/
export async function overrideRepositoriesLoader(repositories: GetInjectableOptions<'repository'>): Promise<void> {
export async function overrideRepositoriesLoader(
repositories: GetInjectableOptions<'repository'>,
container: MedusaContainer
): Promise<void> {
logger.log('Loading overridden entities into the underlying @medusajs');

let count = 0;
for (const repositoryOptions of repositories) {
if (repositoryOptions.override) {
await overrideRepository(repositoryOptions);
await overrideRepository(container, repositoryOptions);
logger.log(`Repository overridden - ${repositoryOptions.metatype.name}`);
++count;
}
Expand All @@ -62,20 +74,15 @@ function registerRepository(container: MedusaContainer, repositoryOptions: GetIn
});
}

async function overrideRepository(repositoryOptions: GetInjectableOption<'repository'>): Promise<void> {
const { metatype, override } = repositoryOptions;
function overrideRepository(container: MedusaContainer, repositoryOptions: GetInjectableOption<'repository'>): void {
const { metatype, repository, override } = repositoryOptions;

const nameParts = override.name.split('Repository');
const keptNameParts = nameParts.length > 1 ? nameParts.splice(nameParts.length - 2, 1) : nameParts;
const name = keptNameParts.length > 1 ? keptNameParts.join('') : keptNameParts[0];
const fileName = `${name.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase()}`;
// @ts-ignore
const { target, manager, queryRunner, metadata, ...custom } = repository;

const originalRepository = await import('@medusajs/medusa/dist/repositories/' + fileName);
const originalRepositoryIndex = getMetadataArgsStorage().entityRepositories.findIndex((repository) => {
return repository.target.name === override.name && repository.target !== metatype;
});
if (originalRepositoryIndex > -1) {
getMetadataArgsStorage().entityRepositories.splice(originalRepositoryIndex, 1);
}
originalRepository[override.name] = metatype;
Object.assign(override, custom);

const formattedName = lowerCaseFirst(metatype.name);
container.cache.delete(formattedName);
container.register(formattedName, asValue(override));
}
3 changes: 2 additions & 1 deletion src/loaders/services.loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export async function servicesLoader(services: GetInjectableOptions<'service'>):

const serviceLoader = await import('@medusajs/medusa/dist/loaders/services');
const originalServiceLoader = serviceLoader.default;
serviceLoader.default = ({ container, configModule, isTest }) => {
serviceLoader.default = async ({ container, configModule, isTest }) => {
originalServiceLoader({ container, configModule, isTest });
for (const serviceOptions of services) {
if (serviceOptions.override) {
Expand Down Expand Up @@ -57,6 +57,7 @@ export function overrideService(
): void {
const { metatype, override, scope } = serviceOptions;
const formattedName = lowerCaseFirst(override.name);

container.cache.delete(formattedName);
container.register({
[formattedName]: asFunction((cradle) => new metatype(cradle, configModule), {
Expand Down
21 changes: 9 additions & 12 deletions src/modules/multi-tenancy/tenant.service.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { Service } from '../../decorators';
import { Connection, createConnection, EntityManager, getConnectionManager } from 'typeorm';
import { ShortenedNamingStrategy } from '@medusajs/medusa/dist/utils/naming-strategy';
import { DataSource, EntityManager } from 'typeorm';
import { ConfigModule } from './types';
import { MedusaRequest } from '../../core';
import { getConfigFile } from 'medusa-core-utils';

@Service()
export class TenantService {
connections: Map<string, DataSource> = new Map();
static readonly resolutionKey = 'tenantService';

/**
Expand Down Expand Up @@ -37,31 +37,28 @@ export class TenantService {
);
}

const connectionManager = getConnectionManager();

let connection!: Connection;
if (connectionManager.has(tenant.code)) {
connection = await connectionManager.get(tenant.code);
let connection!: DataSource;
if (this.connections.has(tenant.code)) {
connection = await this.connections.get(tenant.code);
} else {
const db_entities = req.scope.resolve('db_entities') as any[];
await createConnection({
connection = new DataSource({
name: tenant.code,
type: tenant.database_config.database_type as any,
url: tenant.database_config.database_url,
database: tenant.database_config.database_database,
extra: tenant.database_config.database_extra || {},
entities: db_entities,
namingStrategy: new ShortenedNamingStrategy(),
logging: configModule.projectConfig.database_logging ?? false,
});

connection = await connectionManager.get(tenant.code);
this.connections.set(tenant.code, connection);
}

return await new Promise((resolve) => {
connection.isConnected
connection.isInitialized
? resolve(connection.manager)
: connection.connect().then((conn) => resolve(conn.manager));
: connection.initialize().then((conn) => resolve(conn.manager));
});
}
}
18 changes: 18 additions & 0 deletions starters/server-1-9-or-above/.env.template
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
PORT=3000

DB_HOST=
DB_PORT=
DB_USERNAME=
DB_PASSWORD=
DB_DATABASE=

JWT_SECRET=
JWT_EXPIRESIN=

COOKIE_SECRET=

REDIS_URL=
REDIS_URI=

ADMIN_CORS=
STORE_CORS=
7 changes: 7 additions & 0 deletions starters/server-1-9-or-above/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
dist
node_modules
tsconfig.tsbuildinfo

.env
.env.local
.env.test
Loading