Skip to content

Commit

Permalink
Update: unified api-response structure
Browse files Browse the repository at this point in the history
  • Loading branch information
emmanuelonah committed Jan 5, 2024
1 parent 731a88d commit 5faf7c1
Show file tree
Hide file tree
Showing 5 changed files with 39 additions and 19 deletions.
18 changes: 18 additions & 0 deletions src/services/api-response/index.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { HttpException } from '../http-exception/index.service';

export interface SuccessType<DataType> {
success: boolean;
data: DataType;
}

export interface ErrorType extends HttpException {}

export class ApiResponse {
public error(statusCode: number, message: string) {
return new HttpException(statusCode, message);
}

public success<D = Record<string, unknown>>(data: D) {
return { success: true, data };
}
}
20 changes: 20 additions & 0 deletions src/services/api-response/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { ApiResponse } from './index.service';

describe('response', () => {
const apiResponse = new ApiResponse();

it('should return success response', () => {
expect(apiResponse.success({ name: 'Foo Bar Baz' })).toMatchObject({
success: true,
data: { name: 'Foo Bar Baz' },
});
});

it('should return error response', () => {
expect(apiResponse.error(400, 'Invalid email')).toMatchObject({
success: false,
statusCode: 400,
message: 'Invalid email',
});
});
});
2 changes: 1 addition & 1 deletion src/services/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export { HttpException } from './http-exception/index.service';
export { response, ResponseType } from './response/index.service';
export { ApiResponse, ErrorType, SuccessType } from './api-response/index.service';
8 changes: 0 additions & 8 deletions src/services/response/index.service.ts

This file was deleted.

10 changes: 0 additions & 10 deletions src/services/response/index.test.ts

This file was deleted.

0 comments on commit 5faf7c1

Please sign in to comment.