Skip to content

Commit

Permalink
featL add base entity (#732)
Browse files Browse the repository at this point in the history
Signed-off-by: hxtree <[email protected]>
  • Loading branch information
hxtree authored Dec 3, 2023
1 parent 2ec7611 commit e0360ff
Show file tree
Hide file tree
Showing 56 changed files with 387 additions and 336 deletions.
2 changes: 1 addition & 1 deletion common/config/rush/browser-approved-packages.json
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,7 @@
},
{
"name": "bson",
"allowedCategories": [ "apis" ]
"allowedCategories": [ "apis", "libraries" ]
},
{
"name": "chokidar",
Expand Down
3 changes: 3 additions & 0 deletions common/config/rush/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion common/config/rush/repo-state.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// DO NOT MODIFY THIS FILE MANUALLY BUT DO COMMIT IT. It is generated and used by Rush.
{
"pnpmShrinkwrapHash": "7fa7a3dcd52d909aaeeeda090420adac8db08c68",
"pnpmShrinkwrapHash": "e1f7bbb05a66ed31d315cf99761e2d8c6db29d1f",
"preferredVersionsHash": "7c6836c4ff2ee31a263e87ea93a487fc752ca3f6"
}
12 changes: 12 additions & 0 deletions libraries/faker-factory/CHANGELOG.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,18 @@
{
"name": "@cats-cradle/faker-factory",
"entries": [
{
"version": "1.2.7",
"tag": "@cats-cradle/faker-factory_v1.2.7",
"date": "Sun, 03 Dec 2023 08:29:38 GMT",
"comments": {
"patch": [
{
"comment": "improve toPojo"
}
]
}
},
{
"version": "1.2.6",
"tag": "@cats-cradle/faker-factory_v1.2.6",
Expand Down
9 changes: 8 additions & 1 deletion libraries/faker-factory/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
# Change Log - @cats-cradle/faker-factory

This log was last generated on Mon, 13 Nov 2023 02:11:53 GMT and should not be manually modified.
This log was last generated on Sun, 03 Dec 2023 08:29:38 GMT and should not be manually modified.

## 1.2.7
Sun, 03 Dec 2023 08:29:38 GMT

### Patches

- improve toPojo

## 1.2.6
Mon, 13 Nov 2023 02:11:53 GMT
Expand Down
2 changes: 1 addition & 1 deletion libraries/faker-factory/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@cats-cradle/faker-factory",
"version": "1.2.6",
"version": "1.2.7",
"main": "./dist/index.js",
"repository": {
"type": "git",
Expand Down
31 changes: 23 additions & 8 deletions libraries/faker-factory/src/pojo.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,42 @@
/**
* toPojo
* @param obj
* @returns
*/
export function toPojo(obj: any): any {
export function toPojoInternal(obj: any, visited: Set<any>): any {
if (obj === null || typeof obj !== 'object') {
return obj;
}

if (visited.has(obj)) {
return {}; // Handle circular reference
}

visited.add(obj);

if (Array.isArray(obj)) {
return obj.map((item) => toPojo(item));
const resultArray = obj.map(item => toPojoInternal(item, visited));
visited.delete(obj);
return resultArray;
}

const result: { [key: string]: any } = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
result[key] = toPojo(obj[key]);
result[key] = toPojoInternal(obj[key], visited);
}
}

visited.delete(obj);

return result;
}

/**
* toPojo
* @param obj
* @returns
*/
export function toPojo(obj: any): any {
const visited = new Set<any>();
return toPojoInternal(obj, visited);
}

export function isPojo(obj: any): boolean {
if (typeof obj !== 'object' || obj === null) {
return false;
Expand Down
17 changes: 17 additions & 0 deletions libraries/nestjs-modules/CHANGELOG.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,23 @@
{
"name": "@cats-cradle/nestjs-modules",
"entries": [
{
"version": "0.2.15",
"tag": "@cats-cradle/nestjs-modules_v0.2.15",
"date": "Sun, 03 Dec 2023 08:29:38 GMT",
"comments": {
"patch": [
{
"comment": "add base entity"
}
],
"dependency": [
{
"comment": "Updating dependency \"@cats-cradle/faker-factory\" to `1.2.7`"
}
]
}
},
{
"version": "0.2.13",
"tag": "@cats-cradle/nestjs-modules_v0.2.13",
Expand Down
9 changes: 8 additions & 1 deletion libraries/nestjs-modules/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
# Change Log - @cats-cradle/nestjs-modules

This log was last generated on Tue, 14 Nov 2023 04:01:09 GMT and should not be manually modified.
This log was last generated on Sun, 03 Dec 2023 08:29:38 GMT and should not be manually modified.

## 0.2.15
Sun, 03 Dec 2023 08:29:38 GMT

### Patches

- add base entity

## 0.2.13
Tue, 14 Nov 2023 04:01:09 GMT
Expand Down
5 changes: 3 additions & 2 deletions libraries/nestjs-modules/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@cats-cradle/nestjs-modules",
"version": "0.2.14",
"version": "0.2.15",
"main": "./dist/index.js",
"repository": {
"type": "git",
Expand Down Expand Up @@ -53,7 +53,8 @@
"@types/uuid": "~9.0.6",
"luxon": "~3.3.0",
"mongodb-memory-server-global": "8.13.0",
"@cats-cradle/validation-schemas": "workspace:*"
"@cats-cradle/validation-schemas": "workspace:*",
"bson": "~6.2.0"
},
"devDependencies": {
"@types/jest": "29.5.8",
Expand Down
6 changes: 2 additions & 4 deletions libraries/nestjs-modules/src/__tests__/books/book.schema.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import { mongoosePagination } from 'ts-mongoose-pagination';
import { BaseEntity } from '../../mongoose';

export type TBookDocument = Book & Document;

@Schema()
export class Book {
@Prop()
id: number;

export class Book extends BaseEntity {
@Prop()
name: string;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Repository } from '../../mongoose/mongoose.repository';
import { BaseRepository } from '../../mongoose/base.repository';
import { TPersonDocument, Person } from './person.schema';

@Injectable()
export class PersonRepository extends Repository<TPersonDocument> {
export class PersonRepository extends BaseRepository<TPersonDocument> {
constructor(
// @ts-ignore
@InjectModel(Person.name) private entity: Model<TPersonDocument>,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import { BaseEntity } from '../../mongoose';

@Schema()
export class Person {
@Prop()
public id!: string;

export class Person extends BaseEntity {
@Prop()
public firstName!: string;

Expand Down
15 changes: 7 additions & 8 deletions libraries/nestjs-modules/src/mongoose/base.entity.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
/* eslint-disable func-names */
import { Prop } from '@nestjs/mongoose';
import { Schema } from 'mongoose';
import { IsDateString, IsUuidV4 } from '@cats-cradle/validation-schemas';
import { v4 } from 'uuid';
import { UUID } from 'bson';

export type BaseEntityProps = '_id' | 'updatedAt' | 'createdAt';

export class BaseEntity {
// @Transform(({ value }) => value.toString())
// _id: ObjectId;
@IsUuidV4()
@Prop({
required: true,
type: String,
default: () => v4(),
type: Schema.Types.UUID,
default: () => new UUID(),
})
public _id!: string; // TODO can this be id: ?
_id!: string;

@IsDateString()
@Prop({
Expand All @@ -28,8 +31,4 @@ export class BaseEntity {
default: () => new Date().toISOString(),
})
public createdAt: string;

constructor(partial: NonNullable<BaseEntity>) {
Object.assign(this, partial);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,12 @@ import {
closeInMongodConnection,
rootMongooseTestModule,
} from '../mongoose/mongoose.module';
import { PersonSchema } from './persons/person.schema';
import { PersonRepository } from './persons/person.repository';
import { PersonSchema } from '../__tests__/persons/person.schema';
import { PersonRepository } from '../__tests__/persons/person.repository';
import {
IsDateString,
IsUuidV4Validator,
} from '@cats-cradle/validation-schemas';

describe('MongooseRepository', () => {
let app: INestApplication;
Expand All @@ -31,27 +35,54 @@ describe('MongooseRepository', () => {
app.close();
});

describe('create', () => {
it('should create item', async () => {
const person = await personsRepository.create({
firstName: 'Jane',
lastName: 'Doe',
});

const date = new Date();
expect(IsUuidV4Validator(person!.id)).toBe(true);
expect(IsUuidV4Validator(person!._id)).toBe(true);
expect(person?.createdAt).toContain(date.getFullYear().toString());
expect(person?.updatedAt).toContain(date.getFullYear().toString());
});
});

describe('findOne', () => {
it('should find item in repository', async () => {
await personsRepository.create({
id: 'sss',
it('should find item in repository by id', async () => {
const person = await personsRepository.create({
firstName: 'Jane',
lastName: 'Doe',
});

const result = await personsRepository.findOne({
id: person!.id,
});

expect(result?.firstName).toBe(person?.firstName);
expect(result?.lastName).toBe(person?.lastName);
});

it('should find item in repository by property', async () => {
const person = await personsRepository.create({
firstName: 'Jane',
lastName: 'Doe',
});

expect(result?.firstName).toBe('Jane');
expect(result?.lastName).toBe('Doe');
const result = await personsRepository.findOne({
firstName: 'Jane',
});

expect(result?.firstName).toBe(person?.firstName);
expect(result?.lastName).toBe(person?.lastName);
});
});

describe('findOneOrFail', () => {
it('should find item in repository', async () => {
await personsRepository.create({
id: 'sss',
firstName: 'Jane',
lastName: 'Doe',
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ import {
UpdateQuery,
UpdateWithAggregationPipeline,
Document,
ObjectId,
} from 'mongoose';
import { UUID, ObjectId } from 'bson';
import { v4 } from 'uuid';

export type UpdateModelResponse = {
matchedCount: number;
Expand All @@ -21,13 +22,14 @@ export type DeleteModelResponse = {
deleted: boolean;
};

export class Repository<T extends Document> {
export class BaseRepository<T extends Document> {
constructor(private readonly model: Model<T>) {}

async create(doc: object): Promise<T | null> {
// eslint-disable-next-line new-cap
const createdEntity = new this.model(doc);
return await createdEntity.save();
const createdEntity = new this.model({ ...doc });
await createdEntity.save();

return createdEntity;
}

async findOne(
Expand Down
2 changes: 1 addition & 1 deletion libraries/nestjs-modules/src/mongoose/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export { MongooseModule, MongooseModuleOptions } from '@nestjs/mongoose';
export * from './mongoose.module';
export * from './mongoose.repository';
export * from './base.repository';
export { BaseEntity, BaseEntityProps } from './base.entity';
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import {
closeInMongodConnection,
rootMongooseTestModule,
} from '../mongoose/mongoose.module';
import { BookSchema } from './books/book.schema';
import { BooksRepository } from './books/book.repository';
import { CreateBookDto } from './books/create-book.dto';
import { BookSchema } from '../__tests__/books/book.schema';
import { BooksRepository } from '../__tests__/books/book.repository';
import { CreateBookDto } from '../__tests__/books/create-book.dto';

describe('MongooseModule', () => {
let app: INestApplication;
Expand Down
Loading

0 comments on commit e0360ff

Please sign in to comment.