Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ flowchart LR
| 실행 구성 | 소스 | 책임 |
| --- | --- | --- |
| Firebase Hosting | `firebase.json` | 공개 요청 진입점과 경로별 rewrite 순서 관리 |
| Cloud Run `api-v2` | `nestjs-api` | Todo, PushNotification 요청의 Firebase ID Token 검증과 삭제, 개발 목표 완료 판정, Google·Apple·GitHub 인증 관리 |
| Cloud Run `api-v2` | `nestjs-api` | Todo, PushNotification 요청의 Firebase ID Token 검증과 삭제, 개발 목표 완료 판정, 개발 기록 rollback, Google·Apple·GitHub 인증 관리 |
| Cloud Functions `api` | `functions` | Staging의 나머지 `/api/**` 요청에 대한 `404` 응답 경계 유지 |
| Cloud Functions 개별 함수 | `functions` | trigger, Scheduler, Cloud Tasks, FCM 처리 |
| Firebase Auth | — | 인증이 필요한 경로에 전달된 Bearer token 검증 |
Expand Down Expand Up @@ -158,7 +158,7 @@ npm run test:emulator
npm run docker:build
```

`npm run test:emulator`는 `firebase.test.json`의 Firestore emulator를 `demo-devlog` project로 띄워 개발 목표 완료 transaction을 확인합니다. Firebase CLI와 Java가 필요합니다.
`npm run test:emulator`는 `firebase.test.json`의 Firestore emulator를 `demo-devlog` project로 띄워 개발 목표 완료 transaction과 개발 기록 rollback transaction을 확인합니다. Firebase CLI와 Java가 필요합니다.

`functions/node_modules`, `functions/lib`, `nestjs-api/node_modules`, `nestjs-api/dist`는 로컬 생성물입니다. Git에는 포함하지 않습니다.

Expand Down
10 changes: 10 additions & 0 deletions nestjs-api/src/app.module.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { FirebaseAuthGuard } from './auth/firebase-auth.guard';
import { ApiExceptionFilter } from './common/api-exception.filter';
import { AppModule } from './app.module';
import { DevelopmentGoalsModule } from './development-goals/development-goals.module';
import { DevelopmentRecordsModule } from './development-records/development-records.module';
import { GOOGLE_AUTHENTICATION_CONFIGURATION_TOKEN } from './google/google-authentication.configuration';
import { GitHubAuthenticationModule } from './github/github-authentication.module';
import { GoogleAuthenticationModule } from './google/google-authentication.module';
Expand Down Expand Up @@ -107,6 +108,15 @@ describe(AppModule.name, () => {
expect(imports).toContain(DevelopmentGoalsModule);
});

it('DevelopmentRecordsModule을 애플리케이션에 연결한다', () => {
const imports = Reflect.getMetadata(
MODULE_METADATA.IMPORTS,
AppModule,
) as unknown[];

expect(imports).toContain(DevelopmentRecordsModule);
});

it('AppleAuthenticationModule을 애플리케이션에 연결한다', () => {
const imports = Reflect.getMetadata(
MODULE_METADATA.IMPORTS,
Expand Down
2 changes: 2 additions & 0 deletions nestjs-api/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { AppleAuthenticationModule } from './apple/apple-authentication.module';
import { FirebaseAuthGuard } from './auth/firebase-auth.guard';
import { ApiExceptionFilter } from './common/api-exception.filter';
import { DevelopmentGoalsModule } from './development-goals/development-goals.module';
import { DevelopmentRecordsModule } from './development-records/development-records.module';
import { FirebaseModule } from './firebase/firebase.module';
import { GitHubAuthenticationModule } from './github/github-authentication.module';
import { GoogleAuthenticationModule } from './google/google-authentication.module';
Expand All @@ -16,6 +17,7 @@ import { TodosModule } from './todos/todos.module';
imports: [
AppleAuthenticationModule,
DevelopmentGoalsModule,
DevelopmentRecordsModule,
FirebaseModule,
GitHubAuthenticationModule,
GoogleAuthenticationModule,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import {
Body,
Controller,
HttpCode,
HttpStatus,
Param,
Post,
Req,
} from '@nestjs/common';

import { type FirebaseAuthenticatedRequest } from '../auth/firebase-authenticated-request';
import { ApiException } from '../common/api.exception';
import {
type DevelopmentRecordVersionResponse,
DevelopmentRecordsService,
} from './development-records.service';

/** 개발 기록 rollback 요청의 HTTP 경계 */
@Controller('goals/:goalId/records')
export class DevelopmentRecordsController {
/** 개발 기록 rollback 업무 규칙을 제공하는 의존성 주입 */
constructor(private readonly service: DevelopmentRecordsService) {}

/** 인증된 사용자의 개발 기록 rollback 요청 처리 */
@Post(':recordId/rollback')
@HttpCode(HttpStatus.OK)
async rollback(
@Req() request: FirebaseAuthenticatedRequest,
@Param('goalId') goalId: string,
@Param('recordId') recordId: string,
@Body() body: unknown,
): Promise<DevelopmentRecordVersionResponse> {
const uid = requiredUid(request);
const value = bodyRecord(body);

return this.service.rollback(uid, {
goalId: requiredIdentifier('goalId', goalId),
recordId: requiredIdentifier('recordId', recordId),
sourceVersionId: requiredIdentifier(
'sourceVersionId',
value.sourceVersionId,
),
expectedCurrentVersionId: requiredIdentifier(
'expectedCurrentVersionId',
value.expectedCurrentVersionId,
),
});
}
}

/** 인증 Guard가 확인한 사용자 식별자 */
function requiredUid(request: FirebaseAuthenticatedRequest): string {
if (!request.uid) {
throw new ApiException(
HttpStatus.UNAUTHORIZED,
'unauthenticated',
'인증된 사용자가 아닙니다.',
);
}

return request.uid;
}

/** 객체가 아닌 요청 본문을 빈 객체로 바꾼 요청 본문 */
function bodyRecord(body: unknown): Record<string, unknown> {
if (body && typeof body === 'object' && !Array.isArray(body)) {
return body as Record<string, unknown>;
}

return {};
}

/** 앞뒤 공백을 제거하고 경로 구분자를 거부한 문서 식별자 */
// prettier-ignore
function requiredIdentifier(
name: string,
value: unknown,
): string {
const trimmedValue = typeof value === 'string' ? value.trim() : '';
if (!trimmedValue) {
throw new ApiException(
HttpStatus.BAD_REQUEST,
'invalid-argument',
`${name}가 필요합니다.`,
);
}
if (trimmedValue.includes('/')) {
throw new ApiException(
HttpStatus.BAD_REQUEST,
'invalid-argument',
`${name}에 경로 구분자를 포함할 수 없습니다.`,
);
}

return trimmedValue;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { type Provider } from '@nestjs/common';
import { MODULE_METADATA } from '@nestjs/common/constants';

import { FirebaseModule } from '../firebase/firebase.module';
import { DevelopmentRecordsController } from './development-records.controller';
import { DevelopmentRecordsModule } from './development-records.module';
import { DevelopmentRecordsRepository } from './development-records.repository';
import { DevelopmentRecordsService } from './development-records.service';

jest.mock('firebase-admin/app', () => ({
applicationDefault: jest.fn(),
getApps: jest.fn(),
initializeApp: jest.fn(),
}));
jest.mock('firebase-admin/auth', () => ({
getAuth: jest.fn(),
}));
jest.mock('firebase-admin/firestore', () => ({
getFirestore: jest.fn(),
}));

describe(DevelopmentRecordsModule.name, () => {
it('FirebaseModule과 개발 기록 controller, provider를 구성한다', () => {
const imports = Reflect.getMetadata(
MODULE_METADATA.IMPORTS,
DevelopmentRecordsModule,
) as unknown[];
const controllers = Reflect.getMetadata(
MODULE_METADATA.CONTROLLERS,
DevelopmentRecordsModule,
) as unknown[];
const providers = Reflect.getMetadata(
MODULE_METADATA.PROVIDERS,
DevelopmentRecordsModule,
) as Provider[];

expect(imports).toContain(FirebaseModule);
expect(controllers).toContain(DevelopmentRecordsController);
expect(providers).toEqual(
expect.arrayContaining([
DevelopmentRecordsRepository,
DevelopmentRecordsService,
]),
);
});
});
14 changes: 14 additions & 0 deletions nestjs-api/src/development-records/development-records.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';

import { FirebaseModule } from '../firebase/firebase.module';
import { DevelopmentRecordsController } from './development-records.controller';
import { DevelopmentRecordsRepository } from './development-records.repository';
import { DevelopmentRecordsService } from './development-records.service';

/** 개발 기록 rollback 판정과 Firestore transaction의 의존성 경계 */
@Module({
imports: [FirebaseModule],
controllers: [DevelopmentRecordsController],
providers: [DevelopmentRecordsRepository, DevelopmentRecordsService],
})
export class DevelopmentRecordsModule {}
Loading
Loading