Добавлен контроллер пользователей, описана схема, подключен сервис для работы с БД, описана первая ручка для получения списка пользователей

This commit is contained in:
vigdorov
2020-07-26 00:53:58 +03:00
parent 8a809db67d
commit 7c62c57f2d
11 changed files with 392 additions and 54 deletions

View File

@ -1,22 +0,0 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
describe('AppController', () => {
let appController: AppController;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
});

View File

@ -1,12 +0,0 @@
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
}

View File

@ -1,10 +1,24 @@
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UsersController } from './users/users.contoller';
import {MongooseModule} from '@nestjs/mongoose';
import {MONGO_URL, DB_NAME} from './consts';
import {User, UserSchema} from './users/users.schema';
import {UserService} from './users/users.service';
@Module({
imports: [],
controllers: [AppController],
providers: [AppService],
imports: [
MongooseModule.forRoot(`${MONGO_URL}/${DB_NAME}`, {
connectionName: DB_NAME,
}),
MongooseModule.forFeature([
{name: User.name, schema: UserSchema},
], DB_NAME),
],
controllers: [
UsersController,
],
providers: [
UserService,
],
})
export class AppModule {}

View File

@ -1,8 +0,0 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}

11
src/consts.ts Normal file
View File

@ -0,0 +1,11 @@
export const USERS_CONTROLLER = 'users';
export const AUTH_CONTROLLER = 'auth';
export const MONGO_URL = 'mongodb://localhost:27017';
export const DB_NAME = 'auth-service';
export const ALLOW_ORIGIN_ALL: [string, string] = ['Access-Control-Allow-Origin', '*'];
export const ALLOW_CREDENTIALS: [string, string] = ['Access-Control-Allow-Credentials', 'true'];
export const CONTENT_LENGTH: [string, string] = ['Content-Length', '0'];
export const ALLOW_METHOD: [string, string] = ['Access-Control-Allow-Methods', 'GET,HEAD,PUT,PATCH,POST,DELETE'];
export const ALLOW_HEADERS: [string, string] = ['Access-Control-Allow-Headers', 'Version, Authorization, Content-Type, Api-Name'];

View File

@ -1,8 +1,21 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import {NestFactory} from '@nestjs/core';
import {AppModule} from './app.module';
import {SwaggerModule, DocumentBuilder} from '@nestjs/swagger';
import {USERS_CONTROLLER} from './consts';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
const app = await NestFactory.create(AppModule);
const options = new DocumentBuilder()
.setTitle('Auth API')
.setDescription('API для авторизации приложений и работы с пользователями')
.setVersion('1.0.0')
.addTag(USERS_CONTROLLER)
.build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup('api', app, document);
await app.listen(4002);
}
bootstrap();

View File

@ -0,0 +1,36 @@
import {Controller, Get, Req, Post, Options, Header, Delete, HttpCode, Put, UseInterceptors, All} from '@nestjs/common';
import {ApiResponse, ApiTags, ApiParam, ApiBody} from '@nestjs/swagger';
import {ALLOW_ORIGIN_ALL, ALLOW_METHOD, ALLOW_CREDENTIALS, CONTENT_LENGTH, ALLOW_HEADERS, USERS_CONTROLLER} from '../consts';
import {UserService} from './users.service';
import {UserRequest} from './users.schema';
@Controller(USERS_CONTROLLER)
@ApiTags(USERS_CONTROLLER)
export class UsersController {
constructor(
private readonly userService: UserService
) {}
@Get()
@Header(...ALLOW_ORIGIN_ALL)
@ApiResponse({
status: 200,
description: 'Список всех пользователей',
type: [UserRequest]
})
async findAll(): Promise<UserRequest[]> {
return this.userService.findAll();
}
@Options()
@Header(...ALLOW_ORIGIN_ALL)
@Header(...ALLOW_METHOD)
@Header(...ALLOW_CREDENTIALS)
@Header(...CONTENT_LENGTH)
@Header(...ALLOW_HEADERS)
@HttpCode(204)
async options(): Promise<string> {
return '';
}
}

63
src/users/users.schema.ts Normal file
View File

@ -0,0 +1,63 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import {ApiProperty} from '@nestjs/swagger';
interface Token {
token: string;
expired_at: string;
}
export class UserRequest {
@ApiProperty()
login: string;
@ApiProperty()
avatar: string;
@ApiProperty()
is_admin: string;
}
@Schema()
export class User extends Document {
@Prop({
required: true,
unique: true,
type: String,
})
login: string;
@Prop({
required: true,
type: String,
})
password: string;
@Prop({
type: String,
})
avatar: string;
@Prop({
type: Boolean,
})
is_admin: boolean;
@Prop({
type: {
token: String,
expired_at: String,
}
})
access_token: Token;
@Prop({
type: {
token: String,
expired_at: String,
}
})
refresh_token: Token;
}
export const UserSchema = SchemaFactory.createForClass(User);

View File

@ -0,0 +1,20 @@
import {Model, Connection} from 'mongoose';
import {Injectable} from '@nestjs/common';
import {InjectConnection} from '@nestjs/mongoose';
import {DB_NAME, USERS_CONTROLLER} from 'src/consts';
import {User, UserSchema} from './users.schema';
@Injectable()
export class UserService {
constructor(
@InjectConnection(DB_NAME) private dbConnection: Connection,
) {}
get userModel(): Model<User> {
return this.dbConnection.model<User>(USERS_CONTROLLER, UserSchema);
}
findAll(): any {
return this.userModel.find().exec();
}
}