setup project nest js with init icd codes

This commit is contained in:
arifal
2025-08-21 23:31:05 +07:00
commit 21567a0a7c
24 changed files with 11629 additions and 0 deletions

58
.gitignore vendored Normal file
View File

@@ -0,0 +1,58 @@
# compiled output
/dist
/node_modules
/build
# Logs
logs
*.log
npm-debug.log*
pnpm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# temp directory
.temp
.tmp
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
/generated/prisma

4
.prettierrc Normal file
View File

@@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "all"
}

194
README.md Normal file
View File

@@ -0,0 +1,194 @@
<p align="center">
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="Nest Logo" /></a>
</p>
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
[circleci-url]: https://circleci.com/gh/nestjs/nest
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
<p align="center">
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg" alt="Donate us"/></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow" alt="Follow us on Twitter"></a>
</p>
<!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
[![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->
## Description
Claim Guard Backend - A NestJS application for managing ICD-9 and ICD-10 medical codes with Excel import functionality.
## Features
- **ICD Code Management**: Import and manage ICD-9 and ICD-10 medical codes
- **Excel Import**: Read data from Excel files and store in PostgreSQL database
- **Search & Filter**: Search codes by category, code, or display text
- **REST API**: Full REST API endpoints for accessing ICD data
- **Pagination**: Built-in pagination support for large datasets
## ICD Service Endpoints
### Import Data
```bash
POST /icd/import
```
Imports ICD-9 and ICD-10 data from Excel files in the `test/` directory.
### Search Codes
```bash
GET /icd/search?category=ICD10&search=diabetes&page=1&limit=10
```
Search ICD codes with optional filters:
- `category`: Filter by ICD9 or ICD10
- `search`: Search in code or display text
- `page`: Page number (default: 1)
- `limit`: Items per page (default: 10)
### Get Statistics
```bash
GET /icd/statistics
```
Returns count statistics for ICD codes.
## Database Schema
The application uses PostgreSQL with Prisma ORM. The ICD codes are stored in the `icd_codes` table with the following structure:
```sql
CREATE TABLE "icd_codes" (
"id" TEXT PRIMARY KEY DEFAULT gen_random_uuid(),
"code" TEXT UNIQUE NOT NULL,
"display" TEXT NOT NULL,
"version" TEXT NOT NULL,
"category" TEXT NOT NULL, -- "ICD9" or "ICD10"
"createdAt" TIMESTAMP DEFAULT NOW(),
"updatedAt" TIMESTAMP DEFAULT NOW()
);
```
**ID Format**: The `id` field now uses UUID (Universal Unique Identifier) format like `550e8400-e29b-41d4-a716-446655440000` instead of CUID.
## Setup Instructions
1. **Install Dependencies**
```bash
npm install
```
2. **Database Setup**
Create a `.env` file with your PostgreSQL connection:
```bash
DATABASE_URL="postgresql://username:password@localhost:5432/claim_guard_db?schema=public"
```
3. **Generate Prisma Client**
```bash
npx prisma generate
```
4. **Run Database Migrations**
```bash
npx prisma db push
```
5. **Place Excel Files**
Ensure the following files are in the `test/` directory:
- `[PUBLIC] ICD-9CM e-klaim.xlsx`
- `[PUBLIC] ICD-10 e-klaim.xlsx`
The Excel files should have at least 3 columns:
- Column 1: Code
- Column 2: Display/Description
- Column 3: Version
## Project setup
```bash
$ npm install
```
## Compile and run the project
```bash
# development
$ npm run start
# watch mode
$ npm run start:dev
# production mode
$ npm run start:prod
```
## Run tests
```bash
# unit tests
$ npm run test
# e2e tests
$ npm run test:e2e
# test coverage
$ npm run test:cov
```
## Deployment
When you're ready to deploy your NestJS application to production, there are some key steps you can take to ensure it runs as efficiently as possible. Check out the [deployment documentation](https://docs.nestjs.com/deployment) for more information.
If you are looking for a cloud-based platform to deploy your NestJS application, check out [Mau](https://mau.nestjs.com), our official platform for deploying NestJS applications on AWS. Mau makes deployment straightforward and fast, requiring just a few simple steps:
```bash
$ npm install -g @nestjs/mau
$ mau deploy
```
With Mau, you can deploy your application in just a few clicks, allowing you to focus on building features rather than managing infrastructure.
## Resources
Check out a few resources that may come in handy when working with NestJS:
- Visit the [NestJS Documentation](https://docs.nestjs.com) to learn more about the framework.
- For questions and support, please visit our [Discord channel](https://discord.gg/G7Qnnhy).
- To dive deeper and get more hands-on experience, check out our official video [courses](https://courses.nestjs.com/).
- Deploy your application to AWS with the help of [NestJS Mau](https://mau.nestjs.com) in just a few clicks.
- Visualize your application graph and interact with the NestJS application in real-time using [NestJS Devtools](https://devtools.nestjs.com).
- Need help with your project (part-time to full-time)? Check out our official [enterprise support](https://enterprise.nestjs.com).
- To stay in the loop and get updates, follow us on [X](https://x.com/nestframework) and [LinkedIn](https://linkedin.com/company/nestjs).
- Looking for a job, or have a job to offer? Check out our official [Jobs board](https://jobs.nestjs.com).
## Support
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
## Stay in touch
- Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec)
- Website - [https://nestjs.com](https://nestjs.com/)
- Twitter - [@nestframework](https://twitter.com/nestframework)
## License
Nest is [MIT licensed](https://github.com/nestjs/nest/blob/master/LICENSE).

34
eslint.config.mjs Normal file
View File

@@ -0,0 +1,34 @@
// @ts-check
import eslint from '@eslint/js';
import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended';
import globals from 'globals';
import tseslint from 'typescript-eslint';
export default tseslint.config(
{
ignores: ['eslint.config.mjs'],
},
eslint.configs.recommended,
...tseslint.configs.recommendedTypeChecked,
eslintPluginPrettierRecommended,
{
languageOptions: {
globals: {
...globals.node,
...globals.jest,
},
sourceType: 'commonjs',
parserOptions: {
projectService: true,
tsconfigRootDir: import.meta.dirname,
},
},
},
{
rules: {
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-floating-promises': 'warn',
'@typescript-eslint/no-unsafe-argument': 'warn'
},
},
);

8
nest-cli.json Normal file
View File

@@ -0,0 +1,8 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true
}
}

10761
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

75
package.json Normal file
View File

@@ -0,0 +1,75 @@
{
"name": "claim-guard-be",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@nestjs/common": "^11.0.1",
"@nestjs/core": "^11.0.1",
"@nestjs/platform-express": "^11.0.1",
"@prisma/client": "^6.14.0",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
"xlsx": "^0.18.5"
},
"devDependencies": {
"@eslint/eslintrc": "^3.2.0",
"@eslint/js": "^9.18.0",
"@nestjs/cli": "^11.0.0",
"@nestjs/schematics": "^11.0.0",
"@nestjs/testing": "^11.0.1",
"@types/express": "^5.0.0",
"@types/jest": "^30.0.0",
"@types/node": "^22.10.7",
"@types/supertest": "^6.0.2",
"@types/xlsx": "^0.0.35",
"eslint": "^9.18.0",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-prettier": "^5.2.2",
"globals": "^16.0.0",
"jest": "^30.0.0",
"prettier": "^3.4.2",
"prisma": "^6.14.0",
"source-map-support": "^0.5.21",
"supertest": "^7.0.0",
"ts-jest": "^29.2.5",
"ts-loader": "^9.5.2",
"ts-node": "^10.9.2",
"tsconfig-paths": "^4.2.0",
"typescript": "^5.7.3",
"typescript-eslint": "^8.20.0"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}

27
prisma/schema.prisma Normal file
View File

@@ -0,0 +1,27 @@
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
// Looking for ways to speed up your queries, or scale easily with your serverless or edge functions?
// Try Prisma Accelerate: https://pris.ly/cli/accelerate-init
generator client {
provider = "prisma-client-js"
output = "../generated/prisma"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model IcdCode {
id String @id @default(uuid())
code String @unique
display String
version String
category String // "ICD9" or "ICD10"
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@map("icd_codes")
}

View File

@@ -0,0 +1,22 @@
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!');
});
});
});

12
src/app.controller.ts Normal file
View File

@@ -0,0 +1,12 @@
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();
}
}

11
src/app.module.ts Normal file
View File

@@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { IcdModule } from './icd/icd.module';
@Module({
imports: [IcdModule],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}

8
src/app.service.ts Normal file
View File

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

View File

@@ -0,0 +1,6 @@
export class SearchIcdDto {
category?: 'ICD9' | 'ICD10';
search?: string;
page?: number;
limit?: number;
}

80
src/icd/icd.controller.ts Normal file
View File

@@ -0,0 +1,80 @@
import { Controller, Get, Post, Query, Logger } from '@nestjs/common';
import { IcdService } from './icd.service';
import { SearchIcdDto } from './dto/search-icd.dto';
@Controller('icd')
export class IcdController {
private readonly logger = new Logger(IcdController.name);
constructor(private readonly icdService: IcdService) {}
@Post('import')
async importData() {
try {
this.logger.log('Starting ICD data import...');
const result = await this.icdService.importIcdData();
return {
success: true,
message: 'ICD data imported successfully',
data: result,
};
} catch (error) {
this.logger.error('Error importing ICD data:', error);
return {
success: false,
message: 'Failed to import ICD data',
error: error.message,
};
}
}
@Get('search')
async searchIcdCodes(
@Query('category') category?: string,
@Query('search') search?: string,
@Query('page') page?: string,
@Query('limit') limit?: string,
) {
try {
const pageNum = page ? parseInt(page, 10) : 1;
const limitNum = limit ? parseInt(limit, 10) : 10;
const result = await this.icdService.findIcdCodes(
category,
search,
pageNum,
limitNum,
);
return {
success: true,
...result,
};
} catch (error) {
this.logger.error('Error searching ICD codes:', error);
return {
success: false,
message: 'Failed to search ICD codes',
error: error.message,
};
}
}
@Get('statistics')
async getStatistics() {
try {
const stats = await this.icdService.getStatistics();
return {
success: true,
data: stats,
};
} catch (error) {
this.logger.error('Error getting statistics:', error);
return {
success: false,
message: 'Failed to get statistics',
error: error.message,
};
}
}
}

10
src/icd/icd.module.ts Normal file
View File

@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { IcdController } from './icd.controller';
import { IcdService } from './icd.service';
@Module({
controllers: [IcdController],
providers: [IcdService],
exports: [IcdService],
})
export class IcdModule {}

View File

@@ -0,0 +1,25 @@
import { Test, TestingModule } from '@nestjs/testing';
import { IcdService } from './icd.service';
describe('IcdService', () => {
let service: IcdService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [IcdService],
}).compile();
service = module.get<IcdService>(IcdService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
describe('cleanString', () => {
it('should clean string properly', () => {
// Test private method indirectly through public methods
expect(service).toBeDefined();
});
});
});

223
src/icd/icd.service.ts Normal file
View File

@@ -0,0 +1,223 @@
import { Injectable, Logger } from '@nestjs/common';
import { PrismaClient } from '../../generated/prisma';
import * as XLSX from 'xlsx';
import * as path from 'path';
import * as fs from 'fs';
interface IcdData {
code: string;
display: string;
version: string;
}
@Injectable()
export class IcdService {
private readonly logger = new Logger(IcdService.name);
private readonly prisma = new PrismaClient();
async importIcdData(): Promise<{
icd9Count: number;
icd10Count: number;
total: number;
}> {
try {
this.logger.log('Starting ICD data import...');
// Import ICD-9 data
const icd9Data = await this.readExcelFile(
'test/[PUBLIC] ICD-9CM e-klaim.xlsx',
'ICD9',
);
// Import ICD-10 data
const icd10Data = await this.readExcelFile(
'test/[PUBLIC] ICD-10 e-klaim.xlsx',
'ICD10',
);
// Clear existing data
await this.prisma.icdCode.deleteMany({});
this.logger.log('Cleared existing ICD data');
// Insert ICD-9 data
const icd9Count = await this.bulkInsertData(icd9Data, 'ICD9');
this.logger.log(`Imported ${icd9Count} ICD-9 codes`);
// Insert ICD-10 data
const icd10Count = await this.bulkInsertData(icd10Data, 'ICD10');
this.logger.log(`Imported ${icd10Count} ICD-10 codes`);
const total = icd9Count + icd10Count;
this.logger.log(`Total imported: ${total} ICD codes`);
return {
icd9Count,
icd10Count,
total,
};
} catch (error) {
this.logger.error('Error importing ICD data:', error);
throw error;
}
}
private async readExcelFile(
filePath: string,
category: string,
): Promise<IcdData[]> {
try {
const fullPath = path.join(process.cwd(), filePath);
if (!fs.existsSync(fullPath)) {
throw new Error(`File not found: ${fullPath}`);
}
this.logger.log(`Reading ${category} file: ${filePath}`);
const workbook = XLSX.readFile(fullPath);
const sheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[sheetName];
// Convert sheet to JSON
const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
// Skip header row and process data
const icdData: IcdData[] = [];
for (let i = 1; i < jsonData.length; i++) {
const row = jsonData[i] as any[];
if (row && row.length >= 3) {
const code = this.cleanString(row[0]);
const display = this.cleanString(row[1]);
const version = this.cleanString(row[2]);
if (code && display && version) {
icdData.push({
code,
display,
version,
});
}
}
}
this.logger.log(`Found ${icdData.length} valid ${category} records`);
return icdData;
} catch (error) {
this.logger.error(`Error reading ${category} file:`, error);
throw error;
}
}
private async bulkInsertData(
data: IcdData[],
category: string,
): Promise<number> {
try {
const batchSize = 1000;
let totalInserted = 0;
for (let i = 0; i < data.length; i += batchSize) {
const batch = data.slice(i, i + batchSize);
const insertData = batch.map((item) => ({
code: item.code,
display: item.display,
version: item.version,
category,
}));
await this.prisma.icdCode.createMany({
data: insertData,
skipDuplicates: true,
});
totalInserted += batch.length;
this.logger.log(
`Inserted batch ${Math.floor(i / batchSize) + 1} for ${category}: ${batch.length} records`,
);
}
return totalInserted;
} catch (error) {
this.logger.error(`Error inserting ${category} data:`, error);
throw error;
}
}
private cleanString(value: any): string {
if (value === null || value === undefined) {
return '';
}
return String(value).trim();
}
async findIcdCodes(
category?: string,
search?: string,
page: number = 1,
limit: number = 10,
) {
try {
const where: any = {};
if (category) {
where.category = category;
}
if (search) {
where.OR = [
{ code: { contains: search, mode: 'insensitive' } },
{ display: { contains: search, mode: 'insensitive' } },
];
}
const skip = (page - 1) * limit;
const [data, total] = await Promise.all([
this.prisma.icdCode.findMany({
where,
skip,
take: limit,
orderBy: { code: 'asc' },
}),
this.prisma.icdCode.count({ where }),
]);
return {
data,
total,
page,
limit,
totalPages: Math.ceil(total / limit),
};
} catch (error) {
this.logger.error('Error finding ICD codes:', error);
throw error;
}
}
async getStatistics() {
try {
const [icd9Count, icd10Count, total] = await Promise.all([
this.prisma.icdCode.count({ where: { category: 'ICD9' } }),
this.prisma.icdCode.count({ where: { category: 'ICD10' } }),
this.prisma.icdCode.count(),
]);
return {
icd9Count,
icd10Count,
total,
};
} catch (error) {
this.logger.error('Error getting statistics:', error);
throw error;
}
}
async onModuleDestroy() {
await this.prisma.$disconnect();
}
}

8
src/main.ts Normal file
View File

@@ -0,0 +1,8 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();

Binary file not shown.

Binary file not shown.

25
test/app.e2e-spec.ts Normal file
View File

@@ -0,0 +1,25 @@
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { App } from 'supertest/types';
import { AppModule } from './../src/app.module';
describe('AppController (e2e)', () => {
let app: INestApplication<App>;
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
it('/ (GET)', () => {
return request(app.getHttpServer())
.get('/')
.expect(200)
.expect('Hello World!');
});
});

9
test/jest-e2e.json Normal file
View File

@@ -0,0 +1,9 @@
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}

4
tsconfig.build.json Normal file
View File

@@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}

25
tsconfig.json Normal file
View File

@@ -0,0 +1,25 @@
{
"compilerOptions": {
"module": "nodenext",
"moduleResolution": "nodenext",
"resolvePackageJsonExports": true,
"esModuleInterop": true,
"isolatedModules": true,
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2023",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": true,
"forceConsistentCasingInFileNames": true,
"noImplicitAny": false,
"strictBindCallApply": false,
"noFallthroughCasesInSwitch": false
}
}