Template
1
0

feat: modular domain driven boilerplate

This commit is contained in:
2025-09-22 01:29:55 +02:00
parent 2433f59d1a
commit 9be3230c84
160 changed files with 2468 additions and 1525 deletions

View File

@@ -0,0 +1,48 @@
import { Collection, type CollectionOptions, type Db, type Document, type MongoClient } from "mongodb";
import { container } from "./container.ts";
export function getDatabaseAccessor<TSchemas extends Record<string, Document>>(
database: string,
): DatabaseAccessor<TSchemas> {
let instance: Db | undefined;
return {
get db(): Db {
if (instance === undefined) {
instance = this.client.db(database);
}
return instance;
},
get client(): MongoClient {
return container.get("mongo");
},
collection<TSchema extends keyof TSchemas>(
name: TSchema,
options?: CollectionOptions,
): Collection<TSchemas[TSchema]> {
return this.db.collection<TSchemas[TSchema]>(name.toString(), options);
},
};
}
export type DatabaseAccessor<TSchemas extends Record<string, Document>> = {
/**
* Database for given accessor.
*/
db: Db;
/**
* Lazy loaded mongo client.
*/
client: MongoClient;
/**
* Returns a reference to a MongoDB Collection. If it does not exist it will be created implicitly.
*
* Collection namespace validation is performed server-side.
*
* @param name - Collection name we wish to access.
* @param options - Optional settings for the command.
*/
collection<TSchema extends keyof TSchemas>(name: TSchema, options?: CollectionOptions): Collection<TSchemas[TSchema]>;
};

View File

@@ -0,0 +1,27 @@
import { getEnvironmentVariable } from "@platform/config/environment.ts";
import z from "zod";
export const config = {
mongo: {
host: getEnvironmentVariable({
key: "DB_MONGO_HOST",
type: z.string(),
fallback: "localhost",
}),
port: getEnvironmentVariable({
key: "DB_MONGO_PORT",
type: z.coerce.number(),
fallback: "27017",
}),
user: getEnvironmentVariable({
key: "DB_MONGO_USER",
type: z.string(),
fallback: "root",
}),
pass: getEnvironmentVariable({
key: "DB_MONGO_PASSWORD",
type: z.string(),
fallback: "password",
}),
},
};

View File

@@ -0,0 +1,24 @@
import { MongoClient } from "mongodb";
export function getMongoClient(config: MongoConnectionInfo) {
return new MongoClient(getConnectionUrl(config));
}
export function getConnectionUrl({ host, port, user, pass }: MongoConnectionInfo): MongoConnectionUrl {
return `mongodb://${user}:${pass}@${host}:${port}`;
}
/*
|--------------------------------------------------------------------------------
| Types
|--------------------------------------------------------------------------------
*/
export type MongoConnectionUrl = `mongodb://${string}:${string}@${string}:${number}`;
export type MongoConnectionInfo = {
host: string;
port: number;
user: string;
pass: string;
};

View File

@@ -0,0 +1,6 @@
import { Container } from "@valkyr/inverse";
import { MongoClient } from "mongodb";
export const container = new Container<{
mongo: MongoClient;
}>("@platform/database");

3
platform/database/id.ts Normal file
View File

@@ -0,0 +1,3 @@
import type { CreateIndexesOptions, IndexSpecification } from "mongodb";
export const idIndex: [IndexSpecification, CreateIndexesOptions] = [{ id: 1 }, { unique: true }];

View File

@@ -0,0 +1,12 @@
{
"name": "@platform/database",
"version": "0.0.0",
"private": true,
"type": "module",
"dependencies": {
"@platform/config": "workspace:*",
"@valkyr/inverse": "npm:@jsr/valkyr__inverse@1.0.1",
"mongodb": "6.20.0",
"zod": "4.1.11"
}
}

View File

@@ -0,0 +1,30 @@
import type { CreateIndexesOptions, Db, IndexSpecification } from "mongodb";
import { getCollectionsSet } from "./utilities.ts";
/**
* Takes a mongo database and registers the event store collections and
* indexes defined internally.
*
* @param db - Mongo database to register event store collections against.
* @param registrars - List of registrars to register with the database.
* @param logger - Logger method to print internal logs.
*/
export async function register(db: Db, registrars: Registrar[], logger?: (...args: any[]) => any) {
const list = await getCollectionsSet(db);
for (const { name, indexes } of registrars) {
if (list.has(name) === false) {
await db.createCollection(name);
}
for (const [indexSpec, options] of indexes) {
await db.collection(name).createIndex(indexSpec, options);
logger?.("Mongo Event Store > Collection '%s' is indexed [%O] with options %O", name, indexSpec, options ?? {});
}
logger?.("Mongo Event Store > Collection '%s' is registered", name);
}
}
export type Registrar = {
name: string;
indexes: [IndexSpecification, CreateIndexesOptions?][];
};

View File

@@ -0,0 +1,9 @@
import { config } from "./config.ts";
import { getMongoClient } from "./connection.ts";
import { container } from "./container.ts";
export default {
bootstrap: async (): Promise<void> => {
container.set("mongo", getMongoClient(config.mongo));
},
};

View File

@@ -0,0 +1,70 @@
import type { Db } from "mongodb";
import z, { type ZodObject, type ZodType } from "zod";
/**
* TODO ...
*/
export function takeOne<TDocument>(documents: TDocument[]): TDocument | undefined {
return documents[0];
}
/**
* TODO ...
*/
export function makeDocumentParser<TSchema extends ZodObject>(schema: TSchema): ModelParserFn<TSchema> {
return ((value: unknown | unknown[]) => {
if (Array.isArray(value)) {
return value.map((value: unknown) => schema.parse(value));
}
if (value === undefined || value === null) {
return undefined;
}
return schema.parse(value);
}) as ModelParserFn<TSchema>;
}
/**
* TODO ...
*/
export function toParsedDocuments<TSchema extends ZodType>(
schema: TSchema,
): (documents: unknown[]) => Promise<z.infer<TSchema>[]> {
return async function (documents: unknown[]) {
const parsed = [];
for (const document of documents) {
parsed.push(await schema.parseAsync(document));
}
return parsed;
};
}
/**
* TODO ...
*/
export function toParsedDocument<TSchema extends ZodType>(
schema: TSchema,
): (document?: unknown) => Promise<z.infer<TSchema> | undefined> {
return async function (document: unknown) {
if (document === undefined || document === null) {
return undefined;
}
return schema.parseAsync(document);
};
}
/**
* Get a Set of collections that exists on a given mongo database instance.
*
* @param db - Mongo database to fetch collection list for.
*/
export async function getCollectionsSet(db: Db) {
return db
.listCollections()
.toArray()
.then((collections) => new Set(collections.map((c) => c.name)));
}
type ModelParserFn<TSchema extends ZodObject> = {
(value: unknown): z.infer<TSchema> | undefined;
(value: unknown[]): z.infer<TSchema>[];
};