Skip to content

Commit

Permalink
feat(crud-objection): update objection-crud related code to the lates…
Browse files Browse the repository at this point in the history
…t upstream
  • Loading branch information
rychkog committed Jul 5, 2020
1 parent cd72b5d commit a34eded
Show file tree
Hide file tree
Showing 70 changed files with 3,636 additions and 1,290 deletions.
13 changes: 8 additions & 5 deletions integration/crud-objection/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,16 @@ import { CompaniesModule } from './companies/companies.module';
import { ProjectsModule } from './projects/projects.module';
import { UsersModule } from './users/users.module';
import { DatabaseModule } from './database.module';
import { APP_GUARD } from '@nestjs/core';
import { AuthGuard } from './auth.guard';

@Module({
imports: [
DatabaseModule,
CompaniesModule,
ProjectsModule,
UsersModule,
imports: [DatabaseModule, CompaniesModule, ProjectsModule, UsersModule],
providers: [
{
provide: APP_GUARD,
useClass: AuthGuard,
},
],
})
export class AppModule {}
16 changes: 16 additions & 0 deletions integration/crud-objection/auth.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';

import { UsersService } from './users';
import { USER_REQUEST_KEY } from './constants';

@Injectable()
export class AuthGuard implements CanActivate {
constructor(private usersService: UsersService) {}

async canActivate(ctx: ExecutionContext): Promise<boolean> {
const req = ctx.switchToHttp().getRequest();
req[USER_REQUEST_KEY] = await this.usersService.modelClass.query().findById(1);

return true;
}
}
8 changes: 4 additions & 4 deletions integration/crud-objection/base.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ export class BaseModel extends Model {
createdAt: Date;
updatedAt: Date;

$beforeInsert() {
this.createdAt = new Date();
}

$beforeUpdate() {
this.updatedAt = new Date();
}

$beforeInsert() {
this.createdAt = new Date();
}
}
33 changes: 29 additions & 4 deletions integration/crud-objection/companies/companies.controller.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,47 @@
import { Controller } from '@nestjs/common';
import { ApiUseTags } from '@nestjs/swagger';
import { ApiTags } from '@nestjs/swagger';
import { Crud } from '@nestjsx/crud';

import { Company } from './company.model';
import { CompaniesService } from './companies.service';
import { serialize } from './responses';

@Crud({
model: {
type: Company,
},
serialize,
routes: {
deleteOneBase: {
returnDeleted: false,
},
},
query: {
alwaysPaginate: false,
allow: ['name'],
join: {
users: {},
projects: {},
users: {
alias: 'companyUsers',
exclude: ['email'],
eager: true,
},
'users.projects': {
eager: true,
alias: 'usersProjects',
allow: ['name'],
},
'users.projects.company': {
eager: true,
alias: 'usersProjectsCompany',
},
projects: {
eager: true,
select: false,
},
},
},
})
@ApiUseTags('companies')
@ApiTags('companies')
@Controller('companies')
export class CompaniesController {
constructor(public service: CompaniesService) {}
Expand Down
12 changes: 6 additions & 6 deletions integration/crud-objection/companies/company.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,16 +43,16 @@ export class Company extends BaseModel {
modelClass: path.resolve(__dirname, '../users/user.model'),
join: {
from: 'companies.id',
to: 'users.companyId'
}
to: 'users.companyId',
},
},
projects: {
relation: Model.HasManyRelation,
modelClass: path.resolve(__dirname, '../projects/project.model'),
join: {
from: 'companies.id',
to: 'projects.companyId'
}
}
}
to: 'projects.companyId',
},
},
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsString, MaxLength } from 'class-validator';

export class CreateCompanyDto {
@ApiProperty({ type: 'string' })
@IsString()
@MaxLength(100)
name: string;

@ApiProperty({ type: 'string' })
@IsString()
@MaxLength(100)
domain: string;

@ApiProperty({ type: 'string' })
@IsString()
@MaxLength(100)
description: string;
}
5 changes: 5 additions & 0 deletions integration/crud-objection/companies/requests/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { CreateCompanyDto } from './create-company.dto';

export const dto = {
create: CreateCompanyDto,
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { ApiProperty } from '@nestjs/swagger';
import { Exclude } from 'class-transformer';

export class GetCompanyResponseDto {
@ApiProperty({ type: 'number' })
id: string;

@ApiProperty({ type: 'string' })
name: string;

@ApiProperty({ type: 'string' })
domain: string;

@ApiProperty({ type: 'string' })
description: string;

@Exclude()
createdAt: any;

@Exclude()
updatedAt: any;
}
6 changes: 6 additions & 0 deletions integration/crud-objection/companies/responses/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { SerializeOptions } from '@nestjsx/crud';
import { GetCompanyResponseDto } from './get-company-response.dto';

export const serialize: SerializeOptions = {
get: GetCompanyResponseDto,
};
1 change: 1 addition & 0 deletions integration/crud-objection/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const USER_REQUEST_KEY = 'user';
30 changes: 21 additions & 9 deletions integration/crud-objection/database.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,30 @@ import { Global, Module } from '@nestjs/common';
import * as Knex from 'knex';
import { knexSnakeCaseMappers, Model } from 'objection';
import { UserProfile } from './users-profiles';
import { Project } from './projects';
import { Project, UserProject } from './projects';
import { Company } from './companies';
import { User } from './users';
import { KNEX_CONNECTION } from './injection-tokens';
import { UserProject } from './users-projects';
import { Device } from './devices';
import { License, UserLicense } from './users-licenses';
import { Note } from './notes';

const models = [User, Company, Project, UserProfile, UserProject];
const models = [
User,
Company,
Project,
UserProfile,
UserProject,
Device,
License,
UserLicense,
Note,
];

const modelProviders = models.map(model => {
const modelProviders = models.map((model) => {
return {
provide: model.name,
useValue: model
useValue: model,
};
});

Expand All @@ -26,18 +38,18 @@ const providers = [
client: 'pg',
connection: 'postgres://root:root@127.0.0.1:5455/nestjsx_crud_objection',
debug: process.env.KNEX_DEBUG === 'true',
...knexSnakeCaseMappers()
...knexSnakeCaseMappers(),
});

Model.knex(knex);
return knex;
}
}
},
},
];

@Global()
@Module({
providers: [...providers],
exports: [...providers]
exports: [...providers],
})
export class DatabaseModule {}
18 changes: 18 additions & 0 deletions integration/crud-objection/devices/device.model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { IsOptional, IsString, IsUUID } from 'class-validator';
import { Model } from 'objection';

export class Device extends Model {
static readonly tableName = 'devices';

static get idColumn() {
return ['deviceKey'];
}

@IsOptional({ always: true })
@IsUUID('4', { always: true })
deviceKey: string;

@IsOptional({ always: true })
@IsString({ always: true })
description?: string;
}
29 changes: 29 additions & 0 deletions integration/crud-objection/devices/devices.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { Controller } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Crud } from '@nestjsx/crud';

import { DevicesService } from './devices.service';
import { serialize } from './response';
import { Device } from './device.model';

@Crud({
model: { type: Device },
serialize,
params: {
deviceKey: {
field: 'deviceKey',
type: 'uuid',
primary: true,
},
},
routes: {
deleteOneBase: {
returnDeleted: true,
},
},
})
@ApiTags('devices')
@Controller('/devices')
export class DevicesController {
constructor(public service: DevicesService) {}
}
11 changes: 11 additions & 0 deletions integration/crud-objection/devices/devices.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';

import { DevicesService } from './devices.service';
import { DevicesController } from './devices.controller';

@Module({
providers: [DevicesService],
exports: [DevicesService],
controllers: [DevicesController],
})
export class DevicesModule {}
12 changes: 12 additions & 0 deletions integration/crud-objection/devices/devices.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Inject, Injectable } from '@nestjs/common';

import { Device } from './device.model';
import { ObjectionCrudService } from '@nestjsx/crud-objection';
import { ModelClass } from 'objection';

@Injectable()
export class DevicesService extends ObjectionCrudService<Device> {
constructor(@Inject('Device') modelClass: ModelClass<Device>) {
super(modelClass);
}
}
2 changes: 2 additions & 0 deletions integration/crud-objection/devices/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './device.model';
export * from './devices.service';
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { ApiProperty } from '@nestjs/swagger';
import { Exclude } from 'class-transformer';

export class DeleteDeviceResponseDto {
@ApiProperty({ type: 'string' })
deviceKey: string;

@Exclude()
description?: string;
}
6 changes: 6 additions & 0 deletions integration/crud-objection/devices/response/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { SerializeOptions } from '@nestjsx/crud';
import { DeleteDeviceResponseDto } from './delete-device-response.dto';

export const serialize: SerializeOptions = {
delete: DeleteDeviceResponseDto,
};
6 changes: 4 additions & 2 deletions integration/crud-objection/knexfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@ module.exports = {
migrations: {
directory: './migrations',
stub: './migration.stub',
extension: 'ts',
},
seeds: {
directory: './seeds',
stub: './seed.stub'
stub: './seed.stub',
extension: 'ts',
},
...knexSnakeCaseMappers()
...knexSnakeCaseMappers(),
};
15 changes: 14 additions & 1 deletion integration/crud-objection/main.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,22 @@
import { NestFactory } from '@nestjs/core';
import { ValidationPipe } from '@nestjs/common';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { CrudConfigService } from '@nestjsx/crud';
import { USER_REQUEST_KEY } from './constants';
import { HttpExceptionFilter } from '../shared/https-exception.filter';
import { AppModule } from './app.module';

// Important: load config before (!!!) you import AppModule
// https://github.com/nestjsx/crud/wiki/Controllers#global-options
CrudConfigService.load({
auth: {
property: USER_REQUEST_KEY,
},
routes: {
// exclude: ['createManyBase'],
},
});

async function bootstrap() {
const app = await NestFactory.create(AppModule);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ export async function up(knex: Knex) {
.notNullable()
.unique();

t.jsonb('name').nullable();

t.boolean('is_active')
.notNullable()
.defaultTo(true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ export async function up(knex: Knex) {
.inTable('projects')
.onDelete('CASCADE');

t.text('review').nullable();

t.unique(['user_id', 'project_id']);

t.timestamps();
Expand Down
Loading

0 comments on commit a34eded

Please sign in to comment.