Skip to content
Snippets Groups Projects
Commit 685bd57a authored by Manjunath Kumar's avatar Manjunath Kumar
Browse files

fetch-document-by-id-review-changes

parent 47898715
Branches
No related tags found
1 merge request!3fetchdocumentById in dms
/**
@file <file name>
@description <description>
@author <Your Name>
@created <YYYY-MM-DD>
**/
import {Test, TestingModule} from '@nestjs/testing'; import {Test, TestingModule} from '@nestjs/testing';
import {DocumentService} from './document.service'; import {DocumentService} from './document.service';
import {PrismaService} from '../prisma/prisma.service'; import {PrismaService} from '../prisma/prisma.service';
import { import {
UploadDocumentRequestDto, UploadDocumentRequestDto,
Source Source,
} from './dto/upload-document-request-dto'; } from './dto/upload-document-request-dto';
import {FileNetClient, AppException} from 'nest-common-utilities'; import {FileNetClient, AppException} from 'nest-common-utilities';
...@@ -114,7 +120,7 @@ describe('DocumentService', () => { ...@@ -114,7 +120,7 @@ describe('DocumentService', () => {
}); });
describe('fetchDocument()', () => { describe('fetchDocument()', () => {
it('should return presigned URL when usePresignedUrl is true', async () => { it('should return presigned URL when document_link is present', async () => {
const document = { const document = {
document_id: 'doc-id', document_id: 'doc-id',
entity_type: 'HOSPITAL', entity_type: 'HOSPITAL',
...@@ -136,14 +142,13 @@ describe('DocumentService', () => { ...@@ -136,14 +142,13 @@ describe('DocumentService', () => {
updated_at: new Date(), updated_at: new Date(),
}; };
jest.spyOn(service['prisma'].documents, 'findUnique').mockResolvedValue(document); jest.spyOn(service['prisma'].documents, 'findUnique').mockResolvedValue(document);
jest.spyOn(Math, 'random').mockReturnValue(0.8); // force presigned URL path
const result = await service.fetchDocument('doc-id'); const result = await service.fetchDocument('doc-id');
expect(result).toHaveProperty('docName', 'file.pdf'); expect(result).toHaveProperty('docName', 'file.pdf');
expect(result).toHaveProperty('url'); expect(result).toHaveProperty('url');
expect(result).toHaveProperty('expiresAt'); expect(result).toHaveProperty('expiresAt');
}); });
it('should return base64 content when usePresignedUrl is false', async () => { it('should return base64 content when document_link is null', async () => {
const document = { const document = {
document_id: 'doc-id', document_id: 'doc-id',
entity_type: 'HOSPITAL', entity_type: 'HOSPITAL',
...@@ -153,7 +158,7 @@ describe('DocumentService', () => { ...@@ -153,7 +158,7 @@ describe('DocumentService', () => {
document_name: 'file.pdf', document_name: 'file.pdf',
document_path: '/mock/path/file.pdf', document_path: '/mock/path/file.pdf',
document_type_id: 'doc-type-id', document_type_id: 'doc-type-id',
document_link: 'some-link', document_link: null,
tags: {}, tags: {},
reference_id: null, reference_id: null,
filenet_property_type: null, filenet_property_type: null,
...@@ -163,10 +168,8 @@ describe('DocumentService', () => { ...@@ -163,10 +168,8 @@ describe('DocumentService', () => {
updated_by: 'user-uuid', updated_by: 'user-uuid',
created_at: new Date(), created_at: new Date(),
updated_at: new Date(), updated_at: new Date(),
}; };
jest.spyOn(service['prisma'].documents, 'findUnique').mockResolvedValue(document); jest.spyOn(service['prisma'].documents, 'findUnique').mockResolvedValue(document);
jest.spyOn(Math, 'random').mockReturnValue(0.2); // force base64 path
const result = await service.fetchDocument('doc-id'); const result = await service.fetchDocument('doc-id');
expect(result).toHaveProperty('fileName', 'file.pdf'); expect(result).toHaveProperty('fileName', 'file.pdf');
expect(result).toHaveProperty('mimeType', 'application/pdf'); expect(result).toHaveProperty('mimeType', 'application/pdf');
......
...@@ -5,7 +5,10 @@ ...@@ -5,7 +5,10 @@
@created <YYYY-MM-DD> @created <YYYY-MM-DD>
**/ **/
import {Injectable, NotFoundException, InternalServerErrorException} from '@nestjs/common'; import {
Injectable,
NotFoundException,
} from '@nestjs/common';
import { import {
PrismaService, PrismaService,
} from '../prisma/prisma.service'; } from '../prisma/prisma.service';
...@@ -125,24 +128,24 @@ export class DocumentService { ...@@ -125,24 +128,24 @@ export class DocumentService {
* @param documentId * @param documentId
*/ */
async fetchDocument(documentId: string) { async fetchDocument(documentId: string) {
const document = await this.prisma.documents.findUnique({ const document = await this.prisma.documents.findUnique(
where: {document_id: documentId}, {
}); where: {
document_id: documentId,
},
},
);
if (!document) throw new NotFoundException('Document not found'); if (!document) throw new NotFoundException('Document not found');
try { try {
// const file = await this.fileNetClient.get(document.document_id);//mock // const file = await this.fileNetClient.get(document.document_id);//mock
if (document.source === 'FILENET') { if (document.source === 'FILENET') {
// Mock behavior: randomly return either base64 or presigned URL // Mock behavior: return presigned URL if available, otherwise return file content
const usePresignedUrl = const usePresignedUrl = document.document_link !== null;
document.document_link !== null && Math.random() > 0.5;
if (usePresignedUrl) { if (usePresignedUrl) {
await logInsertToDocumentsAuditLogs( const auditLogArgs = {
this.prisma,
'document_audit_logs',
{
logDetails: { logDetails: {
document_id: document?.document_id, document_id: document?.document_id,
action: Action.FETCH, action: Action.FETCH,
...@@ -152,17 +155,23 @@ export class DocumentService { ...@@ -152,17 +155,23 @@ export class DocumentService {
error_message: null, error_message: null,
created_at: new Date(), created_at: new Date(),
}, },
}); };
await logInsertToDocumentsAuditLogs(
this.prisma,
auditLogArgs,
);
const mockUrl =
`https://mock-storage.com/${document.document_name}` +
`?token=mocked-token`;
const expiresAt = new Date(Date.now() + 15 * 60 * 1000).toISOString();
return { return {
docName: document.document_name, docName: document.document_name,
url: `https://mock-storage.com/${document.document_name}?token=mocked-token`, url: mockUrl,
expiresAt: new Date(Date.now() + 15 * 60 * 1000).toISOString(), expiresAt,
}; };
} else { } else {
await logInsertToDocumentsAuditLogs( const auditLogArgsBase64 = {
this.prisma,
'document_audit_logs',
{
logDetails: { logDetails: {
document_id: document?.document_id, document_id: document?.document_id,
action: Action.FETCH, action: Action.FETCH,
...@@ -172,24 +181,26 @@ export class DocumentService { ...@@ -172,24 +181,26 @@ export class DocumentService {
error_message: null, error_message: null,
created_at: new Date(), created_at: new Date(),
}, },
}, };
await logInsertToDocumentsAuditLogs(
this.prisma,
auditLogArgsBase64,
); );
return { return {
fileName: document.document_name, fileName: document.document_name,
mimeType: 'application/pdf', mimeType: 'application/pdf',
content: Buffer.from( content: Buffer
.from(
`Mock PDF content for ${document.document_name}`, `Mock PDF content for ${document.document_name}`,
).toString('base64'), )
.toString('base64'),
}; };
} }
} }
// return { data: file }; // return { data: file };
} catch (error) { } catch (error) {
console.log('Failed to fetch document:', error.stack); console.log('Failed to fetch document:', error.stack);
await logInsertToDocumentsAuditLogs( const auditLogArgsError = {
this.prisma,
'document_audit_logs',
{
logDetails: { logDetails: {
document_id: document?.document_id, document_id: document?.document_id,
action: Action.FETCH, action: Action.FETCH,
...@@ -199,16 +210,27 @@ export class DocumentService { ...@@ -199,16 +210,27 @@ export class DocumentService {
error_message: error.message, error_message: error.message,
created_at: new Date(), created_at: new Date(),
}, },
}, };
await logInsertToDocumentsAuditLogs(
this.prisma,
auditLogArgsError,
); );
throw new InternalServerErrorException('Failed to fetch document'); throw new AppException('500', error?.message ||
'Failed to fetch document');
} }
} }
} }
interface LogInsertionDocumentsAuditLogsArgs { interface LogInsertionDocumentsAuditLogsArgs {
logDetails: Record<string, any>; logDetails: {
document_id: string;
action: Action;
performed_by: string;
performed_at: Date;
status: Status;
error_message?: string | null;
created_at?: Date;
};
} }
...@@ -220,20 +242,13 @@ interface LogInsertionDocumentsAuditLogsArgs { ...@@ -220,20 +242,13 @@ interface LogInsertionDocumentsAuditLogsArgs {
*/ */
export async function logInsertToDocumentsAuditLogs( export async function logInsertToDocumentsAuditLogs(
prisma: PrismaClient, prisma: PrismaClient,
model: string,
args: LogInsertionDocumentsAuditLogsArgs, args: LogInsertionDocumentsAuditLogsArgs,
): Promise<any> { ): Promise<any> {
const { const {logDetails} = args;
logDetails, await prisma.document_audit_logs.create({
} = args;
await prisma[model].create({
data: { data: {
...logDetails, ...logDetails,
}, },
}); });
return true; return true;
} }
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment