Skip to content
Snippets Groups Projects
Commit 55ebd02c authored by roshan's avatar roshan
Browse files

initial commit with all models added

parent 60d463cc
No related branches found
No related tags found
No related merge requests found
Showing
with 187 additions and 108 deletions
/**
@file <file name>
@description <description>
@author <Your Name>
@created <YYYY-MM-DD>
**/
export const config = ['email', 'phone', 'ssn', 'password', 'dob'];
\ No newline at end of file
/**
@file <file name>
@description <description>
@author <Your Name>
@created <YYYY-MM-DD>
**/
import { Test, TestingModule } from '@nestjs/testing';
import { HospitalController } from './hospital.controller';
......
/**
* @file hospital.controller.ts
* @description Handles HTTP requests related to hospital operations.
* @author <Your Name>
* @created <YYYY-MM-DD>
**/
import { Controller, HttpStatus, Post, HttpException } from '@nestjs/common';
import { Cacheable, Logger } from 'nest-common-utilities';
import { HospitalService } from './hospital.service'
import { HospitalService } from './hospital.service';
/**
* Controller to manage hospital-related API endpoints.
*/
@Controller('hospital')
export class HospitalController {
private logger = new Logger(HospitalController.name);
/**
* Initializes the HospitalController.
*
* @param hospitalService - Service for handling hospital business logic.
*/
constructor(private readonly hospitalService: HospitalService) { }
/**
* Endpoint to create a hospital entry (test operation).
* Logs a user creation attempt and calls the hospital service.
*
* @returns The result of the hospital service test method.
* @throws HttpException if no users are found.
*/
@Post()
@Cacheable((req) => JSON.stringify(req.body), 50)
async create() {
this.logger.info("user create log:::", { email: "roshanadmin@niveus.com" })
this.logger.info("User create log:", { email: "roshanadmin@niveus.com" });
const res = await this.hospitalService.test();
if (!res.total) {
throw new Error('user not foundmgweg')
throw new HttpException('user not found', HttpStatus.BAD_GATEWAY)
throw new HttpException('User not found', HttpStatus.BAD_GATEWAY);
}
return res;
}
}
/**
@file <file name>
@description <description>
@author <Your Name>
@created <YYYY-MM-DD>
**/
import { Module } from '@nestjs/common';
import { HospitalController } from './hospital.controller';
import { PrismaModule } from '../prisma/prisma.module'
import { HospitalService } from './hospital.service';
/**
*
*/
@Module({
imports : [PrismaModule],
controllers: [HospitalController],
......
/**
@file <file name>
@description <description>
@author <Your Name>
@created <YYYY-MM-DD>
**/
import { Test, TestingModule } from '@nestjs/testing';
import { HospitalService } from './hospital.service';
......
/**
* @file hospital.service.ts
* @description Service to handle hospital-related business logic including user fuzzy search operations.
* @author <Your Name>
* @created <YYYY-MM-DD>
**/
import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { fuzzySearch, FuzzySearchResult } from 'nest-common-utilities';
import type { user } from '@prisma/client';
/**
* Service to encapsulate hospital domain logic such as user search.
*/
@Injectable()
export class HospitalService {
/**
* Constructs the HospitalService.
*
* @param prisma - The Prisma service for database interactions.
*/
constructor(private readonly prisma: PrismaService) { }
/**
* Executes a fuzzy search on the user table using the term 'ros'.
*
* @returns A list of users matching the search criteria.
*/
async test(): Promise<FuzzySearchResult<user>> {
const data = await fuzzySearch<user>(this.prisma, 'user', { searchFields: ['name'], searchTerm: 'ros', limit: 10, offset: 0 });
console.log("data::::", data);
return data
const data = await fuzzySearch<user>(this.prisma, 'user', {
searchFields: ['name'],
searchTerm: 'ros',
limit: 10,
offset: 0
});
console.log("Fuzzy search result:", data);
return data;
}
}
/**
* @file main.ts
* @description Entry point for the NestJS application. Bootstraps the app with global middleware,
* exception filters, interceptors, Swagger, security configurations, and microservices.
* @author <Your Name>
* @created <YYYY-MM-DD>
*/
@file <file name>
@description <description>
@author <Your Name>
@created <YYYY-MM-DD>
**/
import { NestFactory, Reflector } from '@nestjs/core';
import { ClassSerializerInterceptor, ValidationPipe } from '@nestjs/common';
......
/**
@file <file name>
@description <description>
@author <Your Name>
@created <YYYY-MM-DD>
**/
import { Module } from '@nestjs/common';
import { ClientsModule, Transport } from '@nestjs/microservices';
import { MicroserviceHealthService } from './microservice.service';
import { CustomClientProviders } from './microservice.registration';
/**
*
*/
@Module({
imports: [
// ClientsModule.register(generateClientRegistrations()),
......
// microservice.registration.ts
/**
@file <file name>
@description <description>
@author <Your Name>
@created <YYYY-MM-DD>
**/
import { ClientProviderOptions, Transport } from '@nestjs/microservices';
import { MICROSERVICE_CONFIGS } from './microservices.config';
import { ClientProxyWrapper, ClientProxyFactory } from 'nest-common-utilities'; // Assuming this is your wrapper class
......
/**
* @file microservice.service.ts
* @description Service for checking the availability of microservices using NestJS ClientProxy communication pattern.
* @author <Your Name>
* @created <YYYY-MM-DD>
**/
import { Injectable } from '@nestjs/common';
import { ModuleRef } from '@nestjs/core';
import { ClientProxy } from '@nestjs/microservices';
import { firstValueFrom } from 'rxjs';
import { Logger } from 'nest-common-utilities';
/**
* MicroserviceHealthService provides methods to check the health of registered microservices.
*/
@Injectable()
export class MicroserviceHealthService {
private logger = new Logger(MicroserviceHealthService.name);
/**
* Initializes the MicroserviceHealthService.
*
* @param moduleRef - Reference to the application module used to resolve dynamic providers.
*/
constructor(
private moduleRef: ModuleRef,
) { }
/**
* Checks if a microservice registered with the given token is available.
* @param token The DI token used to register the microservice (e.g. 'AUTH_SERVICE')
* Checks if a microservice registered with the given token is available by sending a 'ping' command.
*
* @param token - The DI token used to register the microservice (e.g., 'AUTH_SERVICE').
* @returns A promise that resolves to true if the microservice responds with 'pong', otherwise false.
*/
async isServiceAvailable(token: string): Promise<boolean> {
try {
const client: ClientProxy = this.moduleRef.get<ClientProxy>(token, { strict: false });
const result = await client.send({ cmd: 'ping' }, {});
const response = await firstValueFrom(result);
this.logger.info(`Response from microservice ${token}:`, response);
this.logger.info(`Response from microservice "${token}": ${response}`);
return response === 'pong';
} catch (error) {
this.logger.error(`Could not contact microservice ${token}:`, error.message);
this.logger.error(`Failed to contact microservice "${token}": ${error.message}`);
return false;
}
}
/**
* Checks multiple services at once.
* @param tokens List of service tokens to check
* Checks the availability of multiple microservices.
*
* @param tokens - An array of DI tokens representing the microservices to be checked.
* @returns A record mapping each token to a boolean indicating its availability.
*/
async checkMultipleServices(tokens: string[]): Promise<Record<string, boolean>> {
const statuses: Record<string, boolean> = {};
......
/**
@file <file name>
@description <description>
@author <Your Name>
@created <YYYY-MM-DD>
**/
export const MICROSERVICE_CONFIGS = [
{
name: 'CASBIN_SERVICE',
......
/**
@file <file name>
@description <description>
@author <Your Name>
@created <YYYY-MM-DD>
**/
import { Module } from '@nestjs/common';
import { PrismaService } from './prisma.service';
/**
*
*/
@Module({
providers: [PrismaService],
exports: [PrismaService],
})
export class PrismaModule {}
/**
@file <file name>
@description <description>
@author <Your Name>
@created <YYYY-MM-DD>
**/
import { Test, TestingModule } from '@nestjs/testing';
import { PrismaService } from './prisma.service';
describe('PrismaService', () => {
let service: PrismaService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [PrismaService],
}).compile();
service = module.get<PrismaService>(PrismaService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});
// /**
// @file <file name>
// @description <description>
// @author <Your Name>
// @created <YYYY-MM-DD>
// **/
import { Injectable } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';
import { setEncryptedFields, createExtendedPrisma } from 'nest-common-utilities';
import encryptedFields from '../config/prisma.config';
@Injectable()
export class PrismaService extends PrismaClient {
constructor() {
// Call parent constructor first
super();
// Set encrypted field config from host app
setEncryptedFields(encryptedFields);
// Apply Prisma extensions to `this`
const extended = createExtendedPrisma(this);
// Copy properties from extended back into `this`
Object.assign(this, extended);
}
}
\ No newline at end of file
// /**
// @file <file name>
// @description <description>
// @author <Your Name>
// @created <YYYY-MM-DD>
// **/
/**
* @file prisma.service.ts
* @description Custom Prisma service with encrypted field support and extended utilities applied via nest-common-utilities package.
* @author <Your Name>
* @created <YYYY-MM-DD>
**/
import { Injectable } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';
import { setEncryptedFields, createExtendedPrisma } from 'nest-common-utilities';
import encryptedFields from '../config/prisma.config';
/**
* Custom Prisma service that sets up encryption and extensions using `nest-common-utilities`.
*/
@Injectable()
export class PrismaService extends PrismaClient {
/**
* Initializes the Prisma client with encryption settings and extensions.
*/
constructor() {
// Call parent constructor first
// Call the base PrismaClient constructor
super();
// Set encrypted field config from host app
// Set encrypted field configuration from the app's config
setEncryptedFields(encryptedFields);
// Apply Prisma extensions to `this`
// Apply Prisma extensions and enhancements to this instance
const extended = createExtendedPrisma(this);
// Copy properties from extended back into `this`
// Merge the extended client into this instance
Object.assign(this, extended);
}
}
/**
* @file seed.ts
* @description Script to seed initial user data into the database using Prisma and nest-common-utilities helpers.
* @author <Your Name>
* @created <YYYY-MM-DD>
**/
import { seedModel } from 'nest-common-utilities';
import { PrismaService } from './prisma/prisma.service';
// Instantiate Prisma service
const prisma = new PrismaService();
// Sample user data to seed into the database
const userData = [
{ name: 'Roshan', email: 'roshanadmin@niveus.com', hashemail: 'roshanadmin@niveus.com', password: '123456', role: 'admin' },
{ name: 'Roshanuser', email: 'roshanuser@niveus.com', hashemail: 'roshanuser@niveus.com', password: '123456', role: 'user' },
{
name: 'Roshan',
email: 'roshanadmin@niveus.com',
hashemail: 'roshanadmin@niveus.com',
password: '123456',
role: 'admin'
},
{
name: 'Roshanuser',
email: 'roshanuser@niveus.com',
hashemail: 'roshanuser@niveus.com',
password: '123456',
role: 'user'
},
];
/**
* Seeds the user model with initial data.
*/
async function run() {
try {
await seedModel(prisma, 'user' as keyof PrismaService, userData);
console.log('User data seeded successfully.');
} catch (error) {
console.error('Error seeding user data:', error);
} finally {
await prisma.$disconnect();
}
}
// Execute the seed function
run();
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment