@loomcore/api 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/package.json +15 -6
  2. package/dist/__tests__/models/mongo-test-entity.model.d.ts +0 -11
  3. package/dist/__tests__/models/mongo-test-entity.model.js +0 -13
  4. package/dist/__tests__/test-mongo-db.d.ts +0 -14
  5. package/dist/__tests__/test-mongo-db.js +0 -81
  6. package/dist/__tests__/test-user.d.ts +0 -3
  7. package/dist/__tests__/test-user.js +0 -16
  8. package/dist/databases/mongo-db/commands/batch-update.command.d.ts +0 -3
  9. package/dist/databases/mongo-db/commands/batch-update.command.js +0 -41
  10. package/dist/databases/mongo-db/commands/create-many.command.d.ts +0 -5
  11. package/dist/databases/mongo-db/commands/create-many.command.js +0 -17
  12. package/dist/databases/mongo-db/commands/create.command.d.ts +0 -5
  13. package/dist/databases/mongo-db/commands/create.command.js +0 -17
  14. package/dist/databases/mongo-db/commands/delete-by-id.command.d.ts +0 -3
  15. package/dist/databases/mongo-db/commands/delete-by-id.command.js +0 -9
  16. package/dist/databases/mongo-db/commands/delete-many.command.d.ts +0 -4
  17. package/dist/databases/mongo-db/commands/delete-many.command.js +0 -9
  18. package/dist/databases/mongo-db/commands/full-updateby-id.command.d.ts +0 -3
  19. package/dist/databases/mongo-db/commands/full-updateby-id.command.js +0 -21
  20. package/dist/databases/mongo-db/commands/partial-update-by-id.command.d.ts +0 -3
  21. package/dist/databases/mongo-db/commands/partial-update-by-id.command.js +0 -21
  22. package/dist/databases/mongo-db/commands/update.command.d.ts +0 -4
  23. package/dist/databases/mongo-db/commands/update.command.js +0 -19
  24. package/dist/databases/mongo-db/queries/find-one.query.d.ts +0 -3
  25. package/dist/databases/mongo-db/queries/find-one.query.js +0 -9
  26. package/dist/databases/mongo-db/queries/find.query.d.ts +0 -3
  27. package/dist/databases/mongo-db/queries/find.query.js +0 -9
  28. package/dist/databases/mongo-db/queries/get-all.query.d.ts +0 -3
  29. package/dist/databases/mongo-db/queries/get-all.query.js +0 -17
  30. package/dist/databases/mongo-db/queries/get-by-id.query.d.ts +0 -3
  31. package/dist/databases/mongo-db/queries/get-by-id.query.js +0 -20
  32. package/dist/databases/mongo-db/queries/get-count.query.d.ts +0 -2
  33. package/dist/databases/mongo-db/queries/get-count.query.js +0 -5
  34. package/dist/databases/mongo-db/queries/get.query.d.ts +0 -4
  35. package/dist/databases/mongo-db/queries/get.query.js +0 -14
  36. package/dist/databases/postgres/migrations/migration.d.ts +0 -6
  37. package/dist/databases/postgres/migrations/migration.js +0 -14
  38. package/dist/databases/postgres/migrations/runMigrations.d.ts +0 -2
  39. package/dist/databases/postgres/migrations/runMigrations.js +0 -20
  40. package/dist/databases/utils/database-to-idatabase.util.d.ts +0 -3
  41. package/dist/databases/utils/database-to-idatabase.util.js +0 -14
  42. package/dist/models/refresh-token.d.ts +0 -9
  43. package/dist/models/refresh-token.js +0 -2
  44. package/dist/models/refresh-token.spec.d.ts +0 -1
  45. package/dist/models/refresh-token.spec.js +0 -12
  46. package/dist/tsconfig.tsbuildinfo +0 -1
  47. package/dist/utils/sql.db.utils.d.ts +0 -14
  48. package/dist/utils/sql.db.utils.js +0 -94
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@loomcore/api",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "private": false,
5
- "description": "Loom Core Api - An opinionated Node.js api using Typescript, Express, and MongoDb",
5
+ "description": "Loom Core Api - An opinionated Node.js api using Typescript, Express, and MongoDb or PostgreSQL",
6
6
  "scripts": {
7
7
  "clean": "rm -rf dist",
8
8
  "tsc": "tsc --project tsconfig.prod.json",
@@ -17,10 +17,16 @@
17
17
  "install-updated-libs": "npm i @loomcore/models",
18
18
  "update-libs": "npm-run-all -s update-lib-versions install-updated-libs",
19
19
  "typecheck": "tsc",
20
- "test": "cross-env NODE_ENV=test vitest run",
21
- "test:ci": "cross-env NODE_ENV=test vitest run --reporter=json --outputFile=test-results.json",
20
+ "test": "npm-run-all -s test:postgres test:mongodb",
21
+ "test:postgres": "cross-env NODE_ENV=test TEST_DATABASE=postgres vitest run",
22
+ "test:mongodb": "cross-env NODE_ENV=test TEST_DATABASE=mongodb vitest run",
23
+ "test:ci": "npm-run-all -s test:ci:postgres test:ci:mongodb",
24
+ "test:ci:postgres": "cross-env NODE_ENV=test TEST_DATABASE=postgres vitest run --reporter=json --outputFile=test-results-postgres.json",
25
+ "test:ci:mongodb": "cross-env NODE_ENV=test TEST_DATABASE=mongodb vitest run --reporter=json --outputFile=test-results-mongodb.json",
22
26
  "test:watch": "cross-env NODE_ENV=test vitest",
23
- "coverage": "cross-env NODE_ENV=test vitest run --coverage"
27
+ "coverage": "npm-run-all -s coverage:postgres coverage:mongodb",
28
+ "coverage:postgres": "cross-env NODE_ENV=test TEST_DATABASE=postgres vitest run --coverage",
29
+ "coverage:mongodb": "cross-env NODE_ENV=test TEST_DATABASE=mongodb vitest run --coverage"
24
30
  },
25
31
  "author": "Tim Hardy",
26
32
  "license": "Apache 2.0",
@@ -31,6 +37,7 @@
31
37
  "dist/**/*"
32
38
  ],
33
39
  "exports": {
40
+ "./__tests__": "./dist/__tests__/index.js",
34
41
  "./config": "./dist/config/index.js",
35
42
  "./controllers": "./dist/controllers/index.js",
36
43
  "./database": "./dist/database/index.js",
@@ -43,7 +50,6 @@
43
50
  "dependencies": {
44
51
  "jsonwebtoken": "^9.0.2",
45
52
  "node-mailjet": "^6.0.8",
46
- "postgres": "^3.4.7",
47
53
  "qs": "^6.14.0"
48
54
  },
49
55
  "peerDependencies": {
@@ -55,6 +61,7 @@
55
61
  "lodash": "^4.17.21",
56
62
  "moment": "^2.30.1",
57
63
  "mongodb": "^6.16.0",
64
+ "pg": "^8.15.6",
58
65
  "rxjs": "^7.8.0"
59
66
  },
60
67
  "devDependencies": {
@@ -65,6 +72,7 @@
65
72
  "@types/lodash": "^4.17.13",
66
73
  "@types/qs": "^6.14.0",
67
74
  "@types/supertest": "^6.0.3",
75
+ "@types/pg": "^8.15.6",
68
76
  "@vitest/coverage-v8": "^3.0.9",
69
77
  "cross-env": "^7.0.3",
70
78
  "mongodb-memory-server": "^9.3.0",
@@ -72,6 +80,7 @@
72
80
  "rxjs": "^7.8.0",
73
81
  "supertest": "^7.1.0",
74
82
  "typescript": "^5.8.3",
83
+ "pg-mem": "^3.0.5",
75
84
  "vite": "^6.2.5",
76
85
  "vitest": "^3.0.9"
77
86
  }
@@ -1,11 +0,0 @@
1
- import { IAuditable, IEntity, IModelSpec } from "@loomcore/common/models";
2
- import { TSchema } from "@sinclair/typebox";
3
- export declare const MongoTestEntitySchema: TSchema;
4
- export interface MongoTestEntity extends IEntity, IAuditable {
5
- name: string;
6
- description?: string;
7
- isActive?: boolean;
8
- tags?: string[];
9
- count?: number;
10
- }
11
- export declare const mongoTestEntityModelSpec: IModelSpec;
@@ -1,13 +0,0 @@
1
- import { entityUtils } from "@loomcore/common/utils";
2
- import { TypeboxObjectId } from "@loomcore/common/validation";
3
- import { Type } from "@sinclair/typebox";
4
- export const MongoTestEntitySchema = Type.Object({
5
- _id: TypeboxObjectId(),
6
- _orgId: Type.Optional(TypeboxObjectId()),
7
- name: Type.String({ minLength: 1 }),
8
- description: Type.Optional(Type.String()),
9
- isActive: Type.Optional(Type.Boolean()),
10
- tags: Type.Optional(Type.Array(Type.String())),
11
- count: Type.Optional(Type.Number())
12
- });
13
- export const mongoTestEntityModelSpec = entityUtils.getModelSpec(MongoTestEntitySchema, { isAuditable: true });
@@ -1,14 +0,0 @@
1
- import { Db } from 'mongodb';
2
- export declare class TestMongoDb {
3
- private static mongoServer;
4
- private static client;
5
- private static db;
6
- private static initPromise;
7
- static init(): Promise<Db>;
8
- static getRandomId(): string;
9
- private static _performInit;
10
- private static createIndexes;
11
- static getDb(): Db;
12
- static clearCollections(): Promise<void>;
13
- static cleanup(): Promise<void>;
14
- }
@@ -1,81 +0,0 @@
1
- import { MongoMemoryServer } from 'mongodb-memory-server';
2
- import { MongoClient, ObjectId } from 'mongodb';
3
- import testUtils from './common-test.utils.js';
4
- import { initSystemUserContext } from '../config/base-api-config.js';
5
- export class TestMongoDb {
6
- static mongoServer;
7
- static client;
8
- static db;
9
- static initPromise = null;
10
- static async init() {
11
- if (this.initPromise) {
12
- return this.initPromise;
13
- }
14
- this.initPromise = this._performInit();
15
- return this.initPromise;
16
- }
17
- static getRandomId() {
18
- return new ObjectId().toString();
19
- }
20
- static async _performInit() {
21
- if (!this.db) {
22
- this.mongoServer = await MongoMemoryServer.create({
23
- instance: {
24
- ip: '127.0.0.1',
25
- port: 0,
26
- },
27
- binary: {
28
- downloadDir: process.env.HOME ? `${process.env.HOME}/.cache/mongodb-binaries` : undefined,
29
- }
30
- });
31
- const uri = this.mongoServer.getUri();
32
- this.client = await MongoClient.connect(uri);
33
- this.db = this.client.db();
34
- testUtils.initialize(this.db);
35
- await this.createIndexes(this.db);
36
- await testUtils.createMetaOrg();
37
- }
38
- await initSystemUserContext(this.db);
39
- return this.db;
40
- }
41
- static async createIndexes(db) {
42
- await db.command({
43
- createIndexes: "users", indexes: [{ key: { email: 1 }, name: 'email_index', unique: true, collation: { locale: 'en', strength: 1 } }]
44
- });
45
- }
46
- static getDb() {
47
- if (!this.db) {
48
- throw new Error('Database not initialized. Call init() first.');
49
- }
50
- return this.db;
51
- }
52
- static async clearCollections() {
53
- if (!this.db) {
54
- throw new Error('Database not initialized');
55
- }
56
- const collections = await this.db.collections();
57
- for (const collection of collections) {
58
- await collection.deleteMany({});
59
- }
60
- }
61
- static async cleanup() {
62
- await testUtils.cleanup();
63
- if (!this.db) {
64
- throw new Error('Database not initialized');
65
- }
66
- const collections = await this.db.collections();
67
- for (const collection of collections) {
68
- await collection.deleteMany({});
69
- }
70
- if (this.client) {
71
- await this.client.close();
72
- }
73
- if (this.mongoServer) {
74
- await this.mongoServer.stop();
75
- }
76
- this.initPromise = null;
77
- this.db = undefined;
78
- this.client = undefined;
79
- this.mongoServer = undefined;
80
- }
81
- }
@@ -1,3 +0,0 @@
1
- import { IUser, IUserContext } from "@loomcore/common/models";
2
- export declare const testUser: IUser;
3
- export declare const testUserContext: IUserContext;
@@ -1,16 +0,0 @@
1
- export const testUser = {
2
- _id: '67f33ed5b75090e0dda18a3c',
3
- email: 'test@example.com',
4
- password: 'testpassword',
5
- _orgId: '67e8e19b149f740323af93d7',
6
- _created: new Date(),
7
- _createdBy: 'system',
8
- _updated: new Date(),
9
- _updatedBy: 'system',
10
- _deleted: undefined,
11
- _deletedBy: undefined
12
- };
13
- export const testUserContext = {
14
- user: testUser,
15
- _orgId: '67e8e19b149f740323af93d7'
16
- };
@@ -1,3 +0,0 @@
1
- import { Db } from "mongodb";
2
- import { Operation } from "../../operations/operation.js";
3
- export declare function batchUpdate<T>(db: Db, entities: Partial<T>[], operations: Operation[], pluralResourceName: string): Promise<T[]>;
@@ -1,41 +0,0 @@
1
- import { ObjectId } from "mongodb";
2
- import { BadRequestError } from "../../../errors/index.js";
3
- import { convertOperationsToPipeline } from "../utils/index.js";
4
- export async function batchUpdate(db, entities, operations, pluralResourceName) {
5
- const collection = db.collection(pluralResourceName);
6
- if (!entities || entities.length === 0) {
7
- return [];
8
- }
9
- const bulkOperations = [];
10
- const entityIds = [];
11
- for (const entity of entities) {
12
- const { _id, ...updateData } = entity;
13
- if (!_id || !(_id instanceof ObjectId)) {
14
- throw new BadRequestError('Each entity in a batch update must have a valid _id that has been converted to an ObjectId.');
15
- }
16
- entityIds.push(_id);
17
- bulkOperations.push({
18
- updateOne: {
19
- filter: { _id },
20
- update: { $set: updateData },
21
- },
22
- });
23
- }
24
- if (bulkOperations.length > 0) {
25
- await collection.bulkWrite(bulkOperations);
26
- }
27
- const baseQuery = { _id: { $in: entityIds } };
28
- const operationsDocuments = convertOperationsToPipeline(operations);
29
- let updatedEntities;
30
- if (operationsDocuments.length > 0) {
31
- const pipeline = [
32
- { $match: baseQuery },
33
- ...operationsDocuments
34
- ];
35
- updatedEntities = await collection.aggregate(pipeline).toArray();
36
- }
37
- else {
38
- updatedEntities = await collection.find(baseQuery).toArray();
39
- }
40
- return updatedEntities;
41
- }
@@ -1,5 +0,0 @@
1
- import { Db } from "mongodb";
2
- export declare function createMany<T>(db: Db, pluralResourceName: string, entities: Partial<T>[]): Promise<{
3
- insertedIds: any;
4
- entities: any[];
5
- }>;
@@ -1,17 +0,0 @@
1
- import { BadRequestError, DuplicateKeyError } from "../../../errors/index.js";
2
- export async function createMany(db, pluralResourceName, entities) {
3
- try {
4
- const collection = db.collection(pluralResourceName);
5
- const insertResult = await collection.insertMany(entities);
6
- return {
7
- insertedIds: insertResult.insertedIds,
8
- entities: entities
9
- };
10
- }
11
- catch (err) {
12
- if (err.code === 11000) {
13
- throw new DuplicateKeyError(`One or more ${pluralResourceName} already exist`);
14
- }
15
- throw new BadRequestError(`Error creating ${pluralResourceName}`);
16
- }
17
- }
@@ -1,5 +0,0 @@
1
- import { Db } from "mongodb";
2
- export declare function create<T>(db: Db, pluralResourceName: string, entity: any): Promise<{
3
- insertedId: any;
4
- entity: any;
5
- }>;
@@ -1,17 +0,0 @@
1
- import { BadRequestError, DuplicateKeyError } from "../../../errors/index.js";
2
- export async function create(db, pluralResourceName, entity) {
3
- try {
4
- const collection = db.collection(pluralResourceName);
5
- const insertResult = await collection.insertOne(entity);
6
- return {
7
- insertedId: insertResult.insertedId,
8
- entity: entity
9
- };
10
- }
11
- catch (err) {
12
- if (err.code === 11000) {
13
- throw new DuplicateKeyError(`${pluralResourceName} already exists`);
14
- }
15
- throw new BadRequestError(`Error creating ${pluralResourceName}`);
16
- }
17
- }
@@ -1,3 +0,0 @@
1
- import { Db } from "mongodb";
2
- import { DeleteResult as GenericDeleteResult } from "../../models/delete-result.js";
3
- export declare function deleteById(db: Db, id: string, pluralResourceName: string): Promise<GenericDeleteResult>;
@@ -1,9 +0,0 @@
1
- import { ObjectId } from "mongodb";
2
- import { DeleteResult as GenericDeleteResult } from "../../models/delete-result.js";
3
- export async function deleteById(db, id, pluralResourceName) {
4
- const collection = db.collection(pluralResourceName);
5
- const objectId = new ObjectId(id);
6
- const baseQuery = { _id: objectId };
7
- const deleteResult = await collection.deleteOne(baseQuery);
8
- return new GenericDeleteResult(deleteResult.acknowledged, deleteResult.deletedCount);
9
- }
@@ -1,4 +0,0 @@
1
- import { Db } from "mongodb";
2
- import { IQueryOptions } from "@loomcore/common/models";
3
- import { DeleteResult as GenericDeleteResult } from "../../models/delete-result.js";
4
- export declare function deleteMany(db: Db, queryObject: IQueryOptions, pluralResourceName: string): Promise<GenericDeleteResult>;
@@ -1,9 +0,0 @@
1
- import { DeleteResult as GenericDeleteResult } from "../../models/delete-result.js";
2
- import { buildNoSqlMatch } from "../utils/build-no-sql-match.util.js";
3
- export async function deleteMany(db, queryObject, pluralResourceName) {
4
- const collection = db.collection(pluralResourceName);
5
- const matchDocument = buildNoSqlMatch(queryObject);
6
- const filter = matchDocument.$match;
7
- const deleteResult = await collection.deleteMany(filter);
8
- return new GenericDeleteResult(deleteResult.acknowledged, deleteResult.deletedCount);
9
- }
@@ -1,3 +0,0 @@
1
- import { Db } from "mongodb";
2
- import { Operation } from "../../operations/operation.js";
3
- export declare function fullUpdateById<T>(db: Db, operations: Operation[], id: string, entity: any, pluralResourceName: string): Promise<T>;
@@ -1,21 +0,0 @@
1
- import { IdNotFoundError } from "../../../errors/index.js";
2
- import NoSqlPipeline from "../models/no-sql-pipeline.js";
3
- import { buildNoSqlMatch } from "../utils/build-no-sql-match.util.js";
4
- export async function fullUpdateById(db, operations, id, entity, pluralResourceName) {
5
- const collection = db.collection(pluralResourceName);
6
- const matchDocument = buildNoSqlMatch({ filters: { _id: { eq: id } } });
7
- const filter = matchDocument.$match;
8
- const replaceResult = await collection.replaceOne(filter, entity);
9
- if (replaceResult.matchedCount <= 0) {
10
- throw new IdNotFoundError();
11
- }
12
- const pipeline = new NoSqlPipeline()
13
- .addMatch({ filters: { _id: { eq: id } } })
14
- .addOperations(operations)
15
- .build();
16
- const updatedEntity = await collection.aggregate(pipeline).next();
17
- if (!updatedEntity) {
18
- throw new IdNotFoundError();
19
- }
20
- return updatedEntity;
21
- }
@@ -1,3 +0,0 @@
1
- import { Db } from "mongodb";
2
- import { Operation } from "../../operations/operation.js";
3
- export declare function partialUpdateById<T>(db: Db, operations: Operation[], id: string, entity: Partial<any>, pluralResourceName: string): Promise<T>;
@@ -1,21 +0,0 @@
1
- import { IdNotFoundError } from "../../../errors/index.js";
2
- import NoSqlPipeline from "../models/no-sql-pipeline.js";
3
- import { buildNoSqlMatch } from "../utils/build-no-sql-match.util.js";
4
- export async function partialUpdateById(db, operations, id, entity, pluralResourceName) {
5
- const collection = db.collection(pluralResourceName);
6
- const matchDocument = buildNoSqlMatch({ filters: { _id: { eq: id } } });
7
- const filter = matchDocument.$match;
8
- const updatedEntity = await collection.findOneAndUpdate(filter, { $set: entity }, { returnDocument: 'after' });
9
- if (!updatedEntity) {
10
- throw new IdNotFoundError();
11
- }
12
- const pipeline = new NoSqlPipeline()
13
- .addMatch({ filters: { _id: { eq: id } } })
14
- .addOperations(operations)
15
- .build();
16
- const updatedEntityWithOperations = await collection.aggregate(pipeline).next();
17
- if (!updatedEntityWithOperations) {
18
- throw new IdNotFoundError();
19
- }
20
- return updatedEntityWithOperations;
21
- }
@@ -1,4 +0,0 @@
1
- import { Db } from "mongodb";
2
- import { IQueryOptions } from "@loomcore/common/models";
3
- import { Operation } from "../../operations/operation.js";
4
- export declare function update<T>(db: Db, queryObject: IQueryOptions, entity: Partial<any>, operations: Operation[], pluralResourceName: string): Promise<T[]>;
@@ -1,19 +0,0 @@
1
- import { NotFoundError } from "../../../errors/index.js";
2
- import NoSqlPipeline from "../models/no-sql-pipeline.js";
3
- import { buildNoSqlMatch } from "../utils/build-no-sql-match.util.js";
4
- export async function update(db, queryObject, entity, operations, pluralResourceName) {
5
- const collection = db.collection(pluralResourceName);
6
- const matchDocument = buildNoSqlMatch(queryObject);
7
- const filter = matchDocument.$match;
8
- const updateResult = await collection.updateMany(filter, { $set: entity });
9
- if (updateResult.matchedCount <= 0) {
10
- throw new NotFoundError('No records found matching update query');
11
- }
12
- const pipeline = new NoSqlPipeline()
13
- .addMatch(queryObject)
14
- .addOperations(operations)
15
- .addQueryOptions(queryObject, false)
16
- .build();
17
- const updatedEntities = await collection.aggregate(pipeline).toArray();
18
- return updatedEntities;
19
- }
@@ -1,3 +0,0 @@
1
- import { Db } from "mongodb";
2
- import { IQueryOptions } from "@loomcore/common/models";
3
- export declare function findOne<T>(db: Db, queryObject: IQueryOptions, pluralResourceName: string): Promise<T | null>;
@@ -1,9 +0,0 @@
1
- import { buildNoSqlMatch, buildFindOptions } from "../utils/index.js";
2
- export async function findOne(db, queryObject, pluralResourceName) {
3
- const collection = db.collection(pluralResourceName);
4
- const matchDocument = buildNoSqlMatch(queryObject);
5
- const filter = matchDocument.$match;
6
- const options = buildFindOptions(queryObject);
7
- const entity = await collection.findOne(filter, options);
8
- return entity;
9
- }
@@ -1,3 +0,0 @@
1
- import { Db } from "mongodb";
2
- import { IQueryOptions } from "@loomcore/common/models";
3
- export declare function find<T>(db: Db, queryObject: IQueryOptions, pluralResourceName: string): Promise<T[]>;
@@ -1,9 +0,0 @@
1
- import { buildNoSqlMatch, buildFindOptions } from "../utils/index.js";
2
- export async function find(db, queryObject, pluralResourceName) {
3
- const collection = db.collection(pluralResourceName);
4
- const matchDocument = buildNoSqlMatch(queryObject);
5
- const filter = matchDocument.$match;
6
- const options = buildFindOptions(queryObject);
7
- const entities = await collection.find(filter, options).toArray();
8
- return entities;
9
- }
@@ -1,3 +0,0 @@
1
- import { Db } from "mongodb";
2
- import { Operation } from "../../operations/operation.js";
3
- export declare function getAll<T>(db: Db, operations: Operation[], pluralResourceName: string): Promise<T[]>;
@@ -1,17 +0,0 @@
1
- import NoSqlPipeline from "../models/no-sql-pipeline.js";
2
- export async function getAll(db, operations, pluralResourceName) {
3
- const collection = db.collection(pluralResourceName);
4
- const pipeline = new NoSqlPipeline()
5
- .addOperations(operations)
6
- .build();
7
- let aggregateResult;
8
- if (pipeline.length === 0) {
9
- const cursor = collection.find();
10
- aggregateResult = await cursor.toArray();
11
- }
12
- else {
13
- const cursor = collection.aggregate(pipeline);
14
- aggregateResult = await cursor.toArray();
15
- }
16
- return aggregateResult;
17
- }
@@ -1,3 +0,0 @@
1
- import { Db } from "mongodb";
2
- import { Operation } from "../../operations/operation.js";
3
- export declare function getById<T>(db: Db, operations: Operation[], id: string, pluralResourceName: string): Promise<T | null>;
@@ -1,20 +0,0 @@
1
- import { ObjectId } from "mongodb";
2
- import { convertOperationsToPipeline } from "../utils/index.js";
3
- export async function getById(db, operations, id, pluralResourceName) {
4
- const collection = db.collection(pluralResourceName);
5
- const objectId = new ObjectId(id);
6
- const baseQuery = { _id: objectId };
7
- const operationsDocuments = convertOperationsToPipeline(operations);
8
- let entity = null;
9
- if (operationsDocuments.length > 0) {
10
- const pipeline = [
11
- { $match: baseQuery },
12
- ...operationsDocuments
13
- ];
14
- entity = await collection.aggregate(pipeline).next();
15
- }
16
- else {
17
- entity = await collection.findOne(baseQuery);
18
- }
19
- return entity;
20
- }
@@ -1,2 +0,0 @@
1
- import { Db } from "mongodb";
2
- export declare function getCount(db: Db, pluralResourceName: string): Promise<number>;
@@ -1,5 +0,0 @@
1
- export async function getCount(db, pluralResourceName) {
2
- const collection = db.collection(pluralResourceName);
3
- const result = await collection.countDocuments();
4
- return result;
5
- }
@@ -1,4 +0,0 @@
1
- import { Db } from "mongodb";
2
- import { IModelSpec, IQueryOptions, IPagedResult } from "@loomcore/common/models";
3
- import { Operation } from "../../operations/operation.js";
4
- export declare function get<T>(db: Db, operations: Operation[], queryOptions: IQueryOptions, modelSpec: IModelSpec, pluralResourceName: string): Promise<IPagedResult<T>>;
@@ -1,14 +0,0 @@
1
- import NoSqlPipeline from "../models/no-sql-pipeline.js";
2
- import { apiUtils } from "../../../utils/api.utils.js";
3
- export async function get(db, operations, queryOptions, modelSpec, pluralResourceName) {
4
- const collection = db.collection(pluralResourceName);
5
- const pipeline = new NoSqlPipeline()
6
- .addMatch(queryOptions, modelSpec)
7
- .addOperations(operations)
8
- .addQueryOptions(queryOptions, true)
9
- .build();
10
- const cursor = collection.aggregate(pipeline);
11
- const aggregateResult = await cursor.next();
12
- const pagedResult = apiUtils.getPagedResult(aggregateResult?.data || [], aggregateResult?.total || 0, queryOptions);
13
- return pagedResult;
14
- }
@@ -1,6 +0,0 @@
1
- import { Client } from "pg";
2
- export declare class Migration {
3
- private readonly client;
4
- constructor(client: Client);
5
- execute(): Promise<void>;
6
- }
@@ -1,14 +0,0 @@
1
- export class Migration {
2
- client;
3
- constructor(client) {
4
- this.client = client;
5
- }
6
- async execute() {
7
- await this.client.query(`
8
- CREATE TABLE refresh_tokens (
9
- id SERIAL PRIMARY KEY,
10
- token VARCHAR(255) NOT NULL
11
- )
12
- `);
13
- }
14
- }
@@ -1,2 +0,0 @@
1
- import { Client } from "pg";
2
- export declare function runMigrations(client: Client, orgId: string, version?: number | null): Promise<boolean>;
@@ -1,20 +0,0 @@
1
- import { CreateMigrationTableMigration, CreateOrganizationTableMigration, CreateUsersTableMigration } from "./index.js";
2
- import { CreateRefreshTokenTableMigration } from "./004-create-refresh-token-table.migration.js";
3
- export async function runMigrations(client, orgId, version = null) {
4
- const migrations = [
5
- new CreateMigrationTableMigration(client, orgId),
6
- new CreateOrganizationTableMigration(client, orgId),
7
- new CreateUsersTableMigration(client, orgId),
8
- new CreateRefreshTokenTableMigration(client, orgId),
9
- ];
10
- let success = true;
11
- for (const migration of migrations) {
12
- if (version === null || migration.index <= version) {
13
- success = await migration.execute();
14
- if (!success) {
15
- return false;
16
- }
17
- }
18
- }
19
- return success;
20
- }
@@ -1,3 +0,0 @@
1
- import { Database } from "../models/database.js";
2
- import { IDatabase } from "../models/database.interface.js";
3
- export declare function DatabaseToIDatabase(database: Database, pluralResourceName: string): IDatabase;
@@ -1,14 +0,0 @@
1
- import { Db } from "mongodb";
2
- import { MongoDBDatabase } from "../mongo-db/mongo-db.database.js";
3
- import { PostgresDatabase } from "../postgres/postgres.database.js";
4
- export function DatabaseToIDatabase(database, pluralResourceName) {
5
- if (database instanceof Db) {
6
- return new MongoDBDatabase(database, pluralResourceName);
7
- }
8
- else if (database && typeof database === 'object' && 'query' in database && typeof database.query === 'function') {
9
- return new PostgresDatabase(database, pluralResourceName);
10
- }
11
- else {
12
- throw Error('Database is not an instance of Db');
13
- }
14
- }
@@ -1,9 +0,0 @@
1
- import { IEntity } from "@loomcore/common/models";
2
- export interface IRefreshToken extends IEntity {
3
- token: string;
4
- deviceId: string;
5
- userId: string;
6
- expiresOn: number;
7
- created: Date;
8
- createdBy: string;
9
- }
@@ -1,2 +0,0 @@
1
- ;
2
- export {};
@@ -1 +0,0 @@
1
- export declare const refreshTokenModelSpec: import("@loomcore/common/models").IModelSpec<import("@sinclair/typebox").TSchema>;