Skip to content

Commit

Permalink
feat: mongo schema - servince and controller
Browse files Browse the repository at this point in the history
  • Loading branch information
sanriodev committed Sep 10, 2024
1 parent adb7d65 commit 3640c96
Show file tree
Hide file tree
Showing 15 changed files with 358 additions and 22 deletions.
5 changes: 3 additions & 2 deletions src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ModbusReaderModule } from './modules/modbus-reader/modbus-reader.module';
import { AppConfigModule } from './config/config.module';
import { MongoDatabaseProviderModule } from './config/database/mongo/provider/mongo-provider.module';
import { ModbusReaderModule } from './modules/modbus-reader/modbus-reader.module';

@Module({
imports: [ModbusReaderModule, AppConfigModule],
imports: [AppConfigModule, MongoDatabaseProviderModule, ModbusReaderModule],
controllers: [AppController],
providers: [AppService],
})
Expand Down
7 changes: 3 additions & 4 deletions src/config/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ import { registerAs } from '@nestjs/config';

export default registerAs('app', () => ({
port: process.env.APP_PORT,
botToken: process.env.BOT_TOKEN,
publicKey: process.env.APP_PUBLIC_KEY,
clientId: process.env.CLIENT_ID,
serverId: process.env.SERVER_ID,
url: process.env.APP_URL,
name: process.env.APP_NAME,
env: process.env.NODE_ENV,
}));
29 changes: 29 additions & 0 deletions src/config/database/mongo/config/config.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import * as Joi from 'joi';
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import configuration from './configuration';
import { MongoConfigService } from './config.service';
/**
* Import and provide app configuration related classes.
*
* @module
*/
const ENV = process.env.NODE_ENV;
@Module({
imports: [
ConfigModule.forRoot({
load: [configuration],
envFilePath: !ENV ? '.env' : `.env.${ENV}`,
validationSchema: Joi.object({
MONGO_URI: Joi.string().default('localhost'),
MONGO_PORT: Joi.number().default(27017),
MONGO_USERNAME: Joi.string(),
MONGO_PASSWORD: Joi.string(),
MONGO_DATABASE: Joi.string().default(null),
}),
}),
],
providers: [ConfigService, MongoConfigService],
exports: [ConfigService, MongoConfigService],
})
export class MongoConfigModule {}
41 changes: 41 additions & 0 deletions src/config/database/mongo/config/config.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import {
MongooseOptionsFactory,
MongooseModuleOptions,
} from '@nestjs/mongoose';
/**
* Service dealing with app config based operations.
*
* @class
*/
@Injectable()
export class MongoConfigService implements MongooseOptionsFactory {
constructor(private configService: ConfigService) {}

createMongooseOptions(): MongooseModuleOptions {
if (this.username && this.password) {
return {
uri:
`mongodb://${this.username}:${this.password}@${this.uri}` +
(this.database ? `/?authSource=${this.database}` : ''),
dbName: this.database,
};
} else {
return { uri: this.uri };
}
}

get uri(): string {
return this.configService.get<string>('mongo.uri');
}
get username(): string {
return this.configService.get<string>('mongo.username');
}
get password(): string {
return this.configService.get<string>('mongo.password');
}
get database(): string {
return this.configService.get<string>('mongo.database');
}
}
9 changes: 9 additions & 0 deletions src/config/database/mongo/config/configuration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { registerAs } from '@nestjs/config';

export default registerAs('mongo', () => ({
uri: process.env.MONGO_URI,
port: process.env.MONGO_PORT,
username: process.env.MONGO_USERNAME,
password: process.env.MONGO_PASSWORD,
database: process.env.MONGO_DATABASE,
}));
14 changes: 14 additions & 0 deletions src/config/database/mongo/provider/mongo-provider.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { MongooseModule, MongooseModuleAsyncOptions } from '@nestjs/mongoose';
import { MongoConfigModule } from '../config/config.module';
import { MongoConfigService } from '../config/config.service';

@Module({
imports: [
MongooseModule.forRootAsync({
imports: [MongoConfigModule],
useExisting: MongoConfigService,
} as MongooseModuleAsyncOptions),
],
})
export class MongoDatabaseProviderModule {}
15 changes: 15 additions & 0 deletions src/dto/create-energy-entry.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { ApiProperty, OmitType } from '@nestjs/swagger';
import { IsNotEmpty } from 'class-validator';
import { UpdateEnergyEntryDto } from './update-energy-entry.dto';

export class CreateEnergyEntryDto extends OmitType(UpdateEnergyEntryDto, [
'_id',
'batteryLevel',
] as const) {
@ApiProperty({
description: 'The battery level',
example: 100,
})
@IsNotEmpty()
batteryLevel: number;
}
40 changes: 40 additions & 0 deletions src/dto/update-energy-entry.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsOptional } from 'class-validator';
import { ObjectId } from 'mongoose';

export class UpdateEnergyEntryDto {
@ApiProperty({
description: 'The mongo id',
example: '2318931289123890',
})
@IsNotEmpty()
_id: ObjectId;

@ApiProperty({
description: 'The battery level',
example: 100,
})
@IsOptional()
batteryLevel: number;

@ApiProperty({
description: 'The battery level in percent',
example: '45%',
})
@IsOptional()
batteryPercent: string;

@ApiProperty({
description: 'The battery voltage',
example: '5V',
})
@IsOptional()
batteryVoltage: string;

@ApiProperty({
description: 'The battery status',
example: 'charging',
})
@IsOptional()
batteryStatus: string;
}
80 changes: 80 additions & 0 deletions src/modules/energy-entry/energy-entry.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import {
Body,
ClassSerializerInterceptor,
Controller,
Get,
Inject,
Param,
Post,
Put,
UseInterceptors,
UsePipes,
ValidationPipe,
} from '@nestjs/common';
import { ApiOperation, ApiParam, ApiTags } from '@nestjs/swagger';
import { EnergyEntryService } from './energy-entry.service';
import { CreateEnergyEntryDto } from '../../dto/create-energy-entry.dto';
import { ReS } from '../../common/res.model';
import { UpdateEnergyEntryDto } from '../../dto/update-energy-entry.dto';
import { ObjectId } from 'mongoose';

@Controller('energy-data')
@ApiTags('energy-data')
export class EnergyEntryController {
constructor(
@Inject(EnergyEntryService)
private readonly modbusReaderService: EnergyEntryService,
) {}

@Post('/')
@UseInterceptors(ClassSerializerInterceptor)
@UsePipes(new ValidationPipe({ transform: true, whitelist: true }))
@ApiOperation({
summary: 'create enery entry',
description: 'create a new energy entry',
})
async create(@Body() createDto: CreateEnergyEntryDto) {
return ReS.FromData(await this.modbusReaderService.create(createDto));
}

@Put('/')
@UseInterceptors(ClassSerializerInterceptor)
@UsePipes(new ValidationPipe({ transform: true, whitelist: true }))
@ApiOperation({
summary: 'update enery entry',
description: 'update a new energy entry',
})
async update(@Body() updateDto: UpdateEnergyEntryDto) {
return ReS.FromData(await this.modbusReaderService.update(updateDto));
}

@Get('/')
@UseInterceptors(ClassSerializerInterceptor)
@UsePipes(new ValidationPipe({ transform: true, whitelist: true }))
@ApiOperation({
summary: 'get all data',
description: 'get all data from mongo',
})
async getAll() {
return ReS.FromData(await this.modbusReaderService.getAll());
}

@Get('/:id')
@ApiParam({
name: 'id',
description: 'The mongo id',
allowEmptyValue: false,
example: '222222222222222222222222',
required: true,
format: 'string',
})
@UseInterceptors(ClassSerializerInterceptor)
@UsePipes(new ValidationPipe({ transform: true, whitelist: true }))
@ApiOperation({
summary: 'get data by id',
description: 'get data by id from mongo',
})
async get(@Param('id') id: string | ObjectId) {
return ReS.FromData(await this.modbusReaderService.get(id));
}
}
23 changes: 23 additions & 0 deletions src/modules/energy-entry/energy-entry.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { Module } from '@nestjs/common';
import { EnergyEntryService } from './energy-entry.service';
import { EnergyEntryController } from './energy-entry.controller';
import { MongooseModule } from '@nestjs/mongoose';
import {
EnergyEntry,
EnergyEntrySchema,
} from '../../schemas/energy-entry.schema';

@Module({
imports: [
MongooseModule.forFeature([
{
name: EnergyEntry.name,
schema: EnergyEntrySchema,
},
]),
], // Add any imported modules here
controllers: [EnergyEntryController], // Add any controllers here
providers: [EnergyEntryService],
exports: [EnergyEntryService], // Add any providers (services) here
})
export class EnergyEntryModule {}
70 changes: 70 additions & 0 deletions src/modules/energy-entry/energy-entry.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { Injectable, UnprocessableEntityException } from '@nestjs/common';
import {
EnergyEntry,
EnergyEntryDocument,
} from '../../schemas/energy-entry.schema';
import { InjectModel } from '@nestjs/mongoose';
import { Model, ObjectId } from 'mongoose';
import { CreateEnergyEntryDto } from '../../dto/create-energy-entry.dto';
import { UpdateEnergyEntryDto } from '../../dto/update-energy-entry.dto';

@Injectable()
export class EnergyEntryService {
constructor(
@InjectModel(EnergyEntry.name)
private readonly energyEntryModel: Model<EnergyEntryDocument>,
) {}

async create(createDto: CreateEnergyEntryDto): Promise<EnergyEntryDocument> {
try {
return await this.energyEntryModel.create({
batteryLevel: createDto.batteryLevel,
batteryPercent: createDto.batteryPercent,
batteryVoltage: createDto.batteryVoltage,
batteryStatus: createDto.batteryStatus,
occuredAt: new Date(),
});
} catch (error) {
throw new UnprocessableEntityException(error);
}
}

async update(updateDto: UpdateEnergyEntryDto): Promise<EnergyEntryDocument> {
try {
return await this.energyEntryModel.findOneAndUpdate(
{
_id: updateDto._id,
},
{
batteryLevel: updateDto.batteryLevel,
batteryPercent: updateDto.batteryPercent,
batteryVoltage: updateDto.batteryVoltage,
batteryStatus: updateDto.batteryStatus,
},
{
new: true,
},
);
} catch (error) {
throw new UnprocessableEntityException(error);
}
}

async get(id: ObjectId | string): Promise<EnergyEntryDocument> {
try {
return await this.energyEntryModel.findOne({
_id: id,
});
} catch (error) {
throw new UnprocessableEntityException(error);
}
}

async getAll(): Promise<EnergyEntryDocument[]> {
try {
return await this.energyEntryModel.find();
} catch (error) {
throw new UnprocessableEntityException(error);
}
}
}
12 changes: 0 additions & 12 deletions src/modules/modbus-reader/modbus-reader.controller.ts

This file was deleted.

8 changes: 4 additions & 4 deletions src/modules/modbus-reader/modbus-reader.module.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { Module } from '@nestjs/common';
import { ModbusReaderService } from './modbus-reader.service';
import { ModbusReaderController } from './modbus-reader.controller';
import { ModbusReaderService } from './modbus-reder.service';
import { EnergyEntryModule } from '../energy-entry/energy-entry.module';

@Module({
imports: [], // Add any imported modules here
controllers: [ModbusReaderController], // Add any controllers here
imports: [EnergyEntryModule], // Add any imported modules here
controllers: [], // Add any controllers here
providers: [ModbusReaderService],
exports: [ModbusReaderService], // Add any providers (services) here
})
Expand Down
Loading

0 comments on commit 3640c96

Please sign in to comment.