Skip to content

Commit

Permalink
added two other varieties of module registration
Browse files Browse the repository at this point in the history
  • Loading branch information
electricmonk committed May 12, 2024
1 parent 31441c5 commit eb71a1e
Show file tree
Hide file tree
Showing 11 changed files with 192 additions and 16 deletions.
2 changes: 1 addition & 1 deletion packages/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
"fastify": "^4.23.2",
"fastify-type-provider-zod": "^1.1.9",
"mongodb": "^6.1.0",
"nanoid": "^4.0.2",
"nanoid": "^3.3.7",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
"ts-byob": "^1.0.3",
Expand Down
30 changes: 30 additions & 0 deletions packages/server/src/adapters/memory.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import {DynamicModule} from "@nestjs/common";
import {CART_REPO, ORDER_REPO, PRODUCT_REPO} from "./index";
import {MemoryCartRepository} from "./cart.repo";
import {InMemoryOrderRepository, InMemoryProductRepository} from "./fake";
import {ProductTemplate} from "../types";


export class MemoryModule {
static forTests(products: ProductTemplate[]): DynamicModule {
return {
module: MemoryModule,
providers: [

{
provide: PRODUCT_REPO,
useValue: new InMemoryProductRepository(products)
},
{
provide: ORDER_REPO,
useClass: InMemoryOrderRepository,
},
{
provide: CART_REPO,
useClass: MemoryCartRepository,
}
],
exports: [PRODUCT_REPO, ORDER_REPO, CART_REPO]
}
}
}
42 changes: 42 additions & 0 deletions packages/server/src/adapters/mongodb.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import {MongoClient} from "mongodb";
import {DynamicModule} from "@nestjs/common";
import {CART_REPO, ORDER_REPO, PRODUCT_REPO} from "./index";
import {MongoDBProductRepository} from "./product.repo";
import {MongoDBOrderRepository} from "./order.repo";
import {MemoryCartRepository} from "./cart.repo";

export class MongoDBModule {
static forRoot(uri: string): DynamicModule {

return {
module: MongoDBModule,
providers: [
{
provide: "storeDB",
useFactory: async () => {
const mongo = await new MongoClient(uri, {
connectTimeoutMS: 100,
serverSelectionTimeoutMS: 100,
socketTimeoutMS: 100
}).connect();

return mongo.db("store");
},
},
{
provide: PRODUCT_REPO,
useClass: MongoDBProductRepository
},
{
provide: ORDER_REPO,
useClass: MongoDBOrderRepository,
},
{
provide: CART_REPO,
useClass: MemoryCartRepository,
}
],
exports: [PRODUCT_REPO, ORDER_REPO, CART_REPO]
}
}
}
4 changes: 2 additions & 2 deletions packages/server/src/adapters/order.repo.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Collection, Db, ObjectId, WithId } from "mongodb";
import { Order } from "../types";
import {Injectable} from "@nestjs/common";
import {Inject, Injectable} from "@nestjs/common";

type MongoOrder = Omit<Order, "id">;
const docToOrder = ({_id, ...rest}: WithId<MongoOrder>) => Order.parse({id: _id.toString(), ...rest});
Expand All @@ -9,7 +9,7 @@ const docToOrder = ({_id, ...rest}: WithId<MongoOrder>) => Order.parse({id: _id.
export class MongoDBOrderRepository {
private orders: Collection<MongoOrder>;

constructor(db: Db) {
constructor(@Inject("storeDB") db: Db) {
this.orders = db.collection("orders");
}

Expand Down
4 changes: 2 additions & 2 deletions packages/server/src/adapters/product.repo.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { Collection, Db, ObjectId, WithId } from "mongodb";
import { Product, ProductTemplate } from "../types";
import {Injectable} from "@nestjs/common";
import {Inject, Injectable} from "@nestjs/common";

const docToProduct = ({_id, ...rest}: WithId<ProductTemplate>) => Product.parse({id: _id.toString(), ...rest});

@Injectable()
export class MongoDBProductRepository {
private products: Collection<ProductTemplate>;

constructor(db: Db) {
constructor(@Inject("storeDB") db: Db) {
this.products = db.collection("products");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ import {CART_REPO, ORDER_REPO, PRODUCT_REPO} from "./adapters";
import {MemoryCartRepository} from "./adapters/cart.repo";

@Module({})
export class AppModule {
export class AppModuleInversionOfControl {
static register(productRepo: ProductRepository, orderRepo: OrderRepository): DynamicModule {
return {
module: AppModule,
module: AppModuleInversionOfControl,
providers: [
{
provide: PRODUCT_REPO,
Expand Down
11 changes: 11 additions & 0 deletions packages/server/src/app.module.overrides.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Module} from "@nestjs/common";
import {CartController, CheckoutController, OrderController, ProductController} from "./controllers";
import {MongoDBModule} from "./adapters/mongodb.module";

@Module({
imports: [MongoDBModule.forRoot(`mongodb://root:[email protected]`)],
controllers: [CartController, ProductController, OrderController, CheckoutController]
})
export class AppModuleOverrides {

}
14 changes: 14 additions & 0 deletions packages/server/src/app.module.register.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import {DynamicModule, Module} from "@nestjs/common";
import {CartController, CheckoutController, OrderController, ProductController} from "./controllers";


@Module({})
export class AppModuleWithRegister {
static register(adapters: DynamicModule) {
return {
imports: [adapters],
controllers: [CartController, ProductController, OrderController, CheckoutController],
module: AppModuleWithRegister
}
}
}
27 changes: 23 additions & 4 deletions packages/server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,13 @@ import { MongoClient } from "mongodb";
import { MongoDBOrderRepository } from "./adapters/order.repo";
import { MongoDBProductRepository } from "./adapters/product.repo";
import {NestFactory} from "@nestjs/core";
import {AppModule} from "./app.module";
import {AppModuleInversionOfControl} from "./app.module.ioc";
import {AppModuleOverrides} from "./app.module.overrides";
import {AppModuleWithRegister} from "./app.module.register";
import {MongoDBModule} from "./adapters/mongodb.module";

async function startServer() {
// @ts-ignore
async function startServerIoC() {
const mongo = await new MongoClient(
`mongodb://root:[email protected]?retryWrites=true&writeConcern=majority`
).connect();
Expand All @@ -13,11 +17,26 @@ async function startServer() {
const productRepo = new MongoDBProductRepository(db);
const orderRepo = new MongoDBOrderRepository(db);

const app = await NestFactory.create(AppModule.register(productRepo, orderRepo))
const app = await NestFactory.create(AppModuleInversionOfControl.register(productRepo, orderRepo))
app.enableCors({origin: "*"});
await app.listen(8080);
}

void startServer();
// @ts-ignore
async function startServerOverrides() {
const app = await NestFactory.create(AppModuleOverrides)
app.enableCors({origin: "*"});
await app.listen(8080);
}

async function startServerRegister() {
const app = await NestFactory.create(AppModuleWithRegister.register(
MongoDBModule.forRoot(`mongodb://root:[email protected]`)
));
app.enableCors({origin: "*"});
await app.listen(8080);
}

void startServerRegister();


59 changes: 55 additions & 4 deletions packages/server/src/server.testkit.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,68 @@
import {ProductTemplate} from "./types";
import {Test} from "@nestjs/testing";
import {InMemoryOrderRepository, InMemoryProductRepository} from "./adapters/fake";
import {AppModule} from "./app.module";
export async function createTestingModule(products: ProductTemplate[] = []) {
import {AppModuleInversionOfControl} from "./app.module.ioc";
import {AppModuleOverrides} from "./app.module.overrides";
import {ORDER_REPO, PRODUCT_REPO} from "./adapters";
import {MongoDBModule} from "./adapters/mongodb.module";
import {Module} from "@nestjs/common";
import {AppModuleWithRegister} from "./app.module.register";
import {MemoryModule} from "./adapters/memory.module";
export async function createTestingModuleWithIoC(products: ProductTemplate[] = []) {
const productRepo = new InMemoryProductRepository(products);
const orderRepo = new InMemoryOrderRepository();
const testingModule = await Test.createTestingModule({
imports: [AppModule.register(productRepo, orderRepo)],
imports: [AppModuleInversionOfControl.register(productRepo, orderRepo)],
})
.compile();

const nest = testingModule.createNestApplication();
nest.enableCors({origin: "*"});
await nest.init();
return {nest, orderRepo, productRepo};
}
}

export async function createTestingModuleWithOverrides(products: ProductTemplate[] = []) {
const productRepo = new InMemoryProductRepository(products);
const orderRepo = new InMemoryOrderRepository();
const testingModule = await Test.createTestingModule({
imports: [AppModuleOverrides],
})
.overrideModule(MongoDBModule).useModule(NopModule) // this doesn't actually do anything, MongoDB needs to be available for connection even though we don't use it
.overrideProvider(PRODUCT_REPO).useValue(productRepo)
.overrideProvider(ORDER_REPO).useValue(orderRepo)
.compile();

const nest = testingModule.createNestApplication();
nest.enableCors({origin: "*"});
await nest.init();
return {nest, orderRepo, productRepo};
}

export async function createTestingModuleWithRegister(products: ProductTemplate[] = []) {

const testingModule = await Test.createTestingModule({
imports: [AppModuleWithRegister.register(MemoryModule.forTests(products))],
})
.compile();

const productRepo: InMemoryProductRepository = testingModule.get(PRODUCT_REPO);
const orderRepo: InMemoryOrderRepository = testingModule.get(ORDER_REPO);

const nest = testingModule.createNestApplication();
nest.enableCors({origin: "*"});
await nest.init();
return {nest, orderRepo, productRepo};
}

// export const createTestingModule = createTestingModuleWithOverrides;
// export const createTestingModule = createTestingModuleWithIoC;
export const createTestingModule = createTestingModuleWithRegister;

@Module({
providers: [{
provide: "storeDB",
useValue: null
}],
})
class NopModule{}
11 changes: 10 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1964,7 +1964,7 @@ __metadata:
fastify-type-provider-zod: ^1.1.9
jest: ^28.1.3
mongodb: ^6.1.0
nanoid: ^4.0.2
nanoid: ^3.3.7
nodemon: ^3.0.1
reflect-metadata: ^0.2.2
rxjs: ^7.8.1
Expand Down Expand Up @@ -6611,6 +6611,15 @@ __metadata:
languageName: node
linkType: hard

"nanoid@npm:^3.3.7":
version: 3.3.7
resolution: "nanoid@npm:3.3.7"
bin:
nanoid: bin/nanoid.cjs
checksum: d36c427e530713e4ac6567d488b489a36582ef89da1d6d4e3b87eded11eb10d7042a877958c6f104929809b2ab0bafa17652b076cdf84324aa75b30b722204f2
languageName: node
linkType: hard

"nanoid@npm:^4.0.2":
version: 4.0.2
resolution: "nanoid@npm:4.0.2"
Expand Down

0 comments on commit eb71a1e

Please sign in to comment.