├── .dockerignore ├── .eslintrc.js ├── .github └── workflows │ ├── check.yml │ └── test.yml ├── .gitignore ├── .node-version ├── .prettierrc ├── .yarn └── releases │ └── yarn-berry.js ├── .yarnrc.yml ├── Dockerfile ├── README.md ├── bin └── console.ts ├── docker-compose.yml ├── nest-cli.json ├── package.json ├── prisma ├── .env.example ├── migrations │ ├── 20220506060138_create_item │ │ └── migration.sql │ ├── 20220508025559_create_account │ │ └── migration.sql │ └── migration_lock.toml ├── schema.prisma ├── seed.ts └── seeds │ └── 01_Item.ts ├── src ├── app.module.ts ├── controllers │ ├── api │ │ └── v1 │ │ │ ├── item.controller.spec.ts │ │ │ └── item.controller.ts │ ├── root.controller.spec.ts │ └── root.controller.ts ├── i18n │ ├── en.json │ ├── ja.json │ ├── module.ts │ └── utils.ts ├── main.ts └── services │ ├── item │ ├── item.dto.ts │ ├── item.service.spec.ts │ └── item.service.ts │ └── prisma │ ├── prisma.service.spec.ts │ └── prisma.service.ts ├── test ├── app.e2e-spec.ts └── jest-e2e.json ├── tsconfig.build.json ├── tsconfig.json └── yarn.lock /.dockerignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parser: '@typescript-eslint/parser', 3 | parserOptions: { 4 | project: 'tsconfig.json', 5 | tsconfigRootDir : __dirname, 6 | sourceType: 'module', 7 | }, 8 | plugins: ['@typescript-eslint/eslint-plugin'], 9 | extends: [ 10 | 'plugin:@typescript-eslint/recommended', 11 | 'plugin:prettier/recommended', 12 | ], 13 | root: true, 14 | env: { 15 | node: true, 16 | jest: true, 17 | }, 18 | ignorePatterns: ['.eslintrc.js'], 19 | rules: { 20 | '@typescript-eslint/interface-name-prefix': 'off', 21 | '@typescript-eslint/explicit-function-return-type': 'off', 22 | '@typescript-eslint/explicit-module-boundary-types': 'off', 23 | '@typescript-eslint/no-explicit-any': 'off', 24 | }, 25 | }; 26 | -------------------------------------------------------------------------------- /.github/workflows/check.yml: -------------------------------------------------------------------------------- 1 | # This workflow will do a clean installation of node dependencies, cache/restore them, build the source code and run tests across different versions of node 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions 3 | 4 | name: Static analysis checking 5 | 6 | on: 7 | push: 8 | branches: [master] 9 | pull_request: 10 | branches: [master] 11 | 12 | jobs: 13 | build: 14 | runs-on: ubuntu-latest 15 | 16 | steps: 17 | - uses: actions/checkout@v3 18 | - uses: actions/setup-node@v3 19 | with: 20 | node-version: 14.17.0 21 | cache: 'yarn' 22 | - run: yarn install --immutable 23 | - run: yarn lint 24 | - run: yarn typecheck 25 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | # This workflow will do a clean installation of node dependencies, cache/restore them, build the source code and run tests across different versions of node 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions 3 | 4 | name: Node.js Testing 5 | 6 | on: 7 | push: 8 | branches: [master] 9 | pull_request: 10 | branches: [master] 11 | 12 | jobs: 13 | build: 14 | runs-on: ubuntu-latest 15 | 16 | services: 17 | mysql: 18 | image: mysql 19 | ports: 20 | - '3306:3306' 21 | env: 22 | MYSQL_ROOT_PASSWORD: password 23 | MYSQL_DATABASE: develop 24 | MYSQL_USER: user 25 | MYSQL_PASSWORD: password 26 | 27 | steps: 28 | - uses: actions/checkout@v3 29 | - uses: actions/setup-node@v3 30 | with: 31 | node-version: 14.17.0 32 | cache: 'yarn' 33 | - run: yarn install --immutable 34 | - run: | 35 | echo "DATABASE_URL=mysql://root:password@localhost/develop" > ./prisma/.env 36 | - name: prepare 37 | run: | 38 | yarn db:apply 39 | yarn db:seed 40 | - run: yarn test 41 | - run: yarn test:e2e 42 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # compiled output 2 | /dist 3 | /node_modules 4 | 5 | # Logs 6 | logs 7 | *.log 8 | npm-debug.log* 9 | pnpm-debug.log* 10 | yarn-debug.log* 11 | yarn-error.log* 12 | lerna-debug.log* 13 | 14 | # OS 15 | .DS_Store 16 | 17 | # Tests 18 | /coverage 19 | /.nyc_output 20 | 21 | # IDEs and editors 22 | /.idea 23 | .project 24 | .classpath 25 | .c9/ 26 | *.launch 27 | .settings/ 28 | *.sublime-workspace 29 | 30 | # IDE - VSCode 31 | .vscode/* 32 | !.vscode/settings.json 33 | !.vscode/tasks.json 34 | !.vscode/launch.json 35 | !.vscode/extensions.json 36 | 37 | # Database 38 | /prisma/data 39 | /prisma/.env 40 | 41 | # Yarn 42 | .yarn/* 43 | !.yarn/releases 44 | 45 | # Minio 46 | minio/* -------------------------------------------------------------------------------- /.node-version: -------------------------------------------------------------------------------- 1 | 14.17.0 2 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all" 4 | } -------------------------------------------------------------------------------- /.yarnrc.yml: -------------------------------------------------------------------------------- 1 | nodeLinker: node-modules 2 | 3 | yarnPath: .yarn/releases/yarn-berry.js 4 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node 2 | RUN mkdir -p /app 3 | WORKDIR /app 4 | 5 | ADD . ./ 6 | RUN yarn install --immutable 7 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # nestjs-docker-prisma-mysql 2 | 3 | [![Node.js Testing](https://github.com/fsubal/nestjs-docker-prisma-mysql/actions/workflows/test.yml/badge.svg)](https://github.com/fsubal/nestjs-docker-prisma-mysql/actions/workflows/test.yml) 4 | [![Static analysis checking](https://github.com/fsubal/nestjs-docker-prisma-mysql/actions/workflows/check.yml/badge.svg)](https://github.com/fsubal/nestjs-docker-prisma-mysql/actions/workflows/check.yml) 5 | 6 |

7 | Nest Logo 8 |

9 | 10 | Application template for [NestJS](https://github.com/nestjs/nest) + Docker + Prisma + MySQL 11 | 12 | ## Setup 13 | 14 | ```bash 15 | # install 16 | $ yarn 17 | 18 | # Setup env file for database 19 | $ cp prisma/.env.example prisma/.env 20 | 21 | # run containers 22 | $ yarn dev 23 | 24 | # setup database ( sync database schema ) 25 | $ docker exec -it app yarn db:apply 26 | 27 | # insert seed data 28 | $ docker exec -it app yarn db:seed 29 | ``` 30 | 31 | Currently HMR is not enabled, so the server will reload on every file change. 32 | 33 | ## Use Prisma Studio 34 | 35 | You can view / edit DB tables using [Prisma Studio](https://www.prisma.io/studio). 36 | 37 | Once you run `yarn dev`, you can open it in `http://localhost:5555`. 38 | 39 | ## Migration (Development) 40 | 41 | Log in to the `app` container and run 42 | 43 | ```bash 44 | $ docker exec -it app yarn db:migrate:dev 45 | ``` 46 | 47 | ## Swagger 48 | 49 | Swagger UI is available on `http://localhost:3000/api` 50 | 51 | ## Test 52 | 53 | ```bash 54 | # unit tests 55 | $ docker exec -it app yarn test 56 | 57 | # e2e tests 58 | $ docker exec -it app yarn test:e2e 59 | 60 | # test coverage 61 | $ docker exec -it app yarn test:cov 62 | ``` 63 | -------------------------------------------------------------------------------- /bin/console.ts: -------------------------------------------------------------------------------- 1 | import { NestFactory } from '@nestjs/core'; 2 | import { AppModule } from '../src/app.module'; 3 | import { PrismaService } from '../src/services/prisma/prisma.service'; 4 | 5 | async function bootstrap() { 6 | console.log('Initializing console...'); 7 | 8 | const app = await NestFactory.create(AppModule); 9 | 10 | // @ts-expect-error 型 'typeof globalThis' にはインデックス シグネチャがないため、要素は暗黙的に 'any' 型になります。ts(7017) 11 | globalThis.app = app; 12 | 13 | // @ts-expect-error 型 'typeof globalThis' にはインデックス シグネチャがないため、要素は暗黙的に 'any' 型になります。ts(7017) 14 | globalThis.prisma = app.get(PrismaService); 15 | } 16 | 17 | bootstrap(); 18 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.8' 2 | services: 3 | app: 4 | container_name: app 5 | build: . 6 | tty: true 7 | command: yarn run-p start:dev db:studio 8 | ports: 9 | - '3000:3000' 10 | - '5555:5555' 11 | volumes: 12 | - .:/app 13 | depends_on: 14 | - mysql 15 | env_file: 16 | - ./prisma/.env 17 | 18 | mysql: 19 | image: mysql 20 | command: --default-authentication-plugin=mysql_native_password 21 | ports: 22 | - '3306:3306' 23 | environment: 24 | MYSQL_ROOT_PASSWORD: password 25 | MYSQL_DATABASE: develop 26 | MYSQL_USER: user 27 | MYSQL_PASSWORD: password 28 | volumes: 29 | - ./prisma/data:/var/lib/mysql 30 | 31 | minio: 32 | image: minio/minio:latest 33 | container_name: minio 34 | ports: 35 | - 9090:9000 36 | - 33023:33023 37 | environment: 38 | - MINIO_ROOT_USER=root 39 | - MINIO_ROOT_PASSWORD=password 40 | entrypoint: sh 41 | command: -c " 42 | mkdir -p /data/.minio.sys/buckets; 43 | /opt/bin/minio server /data --console-address :33023; 44 | " 45 | volumes: 46 | - ./minio:/data 47 | -------------------------------------------------------------------------------- /nest-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/nest-cli", 3 | "collection": "@nestjs/schematics", 4 | "sourceRoot": "src", 5 | "compilerOptions": { 6 | "plugins": [ 7 | { 8 | "name": "@nestjs/swagger", 9 | "options": { 10 | "classValidatorShim": false, 11 | "introspectComments": true 12 | } 13 | } 14 | ] 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nestjs-docker-prisma-mysql", 3 | "version": "0.0.1", 4 | "description": "", 5 | "author": "", 6 | "private": true, 7 | "license": "UNLICENSED", 8 | "scripts": { 9 | "prebuild": "rimraf dist", 10 | "build": "nest build", 11 | "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", 12 | "dev": "docker compose up -d --build", 13 | "start": "nest start", 14 | "start:dev": "nest start --watch", 15 | "start:debug": "nest start --debug --watch", 16 | "start:prod": "node dist/main", 17 | "console": "ts-node -r ./bin/console.ts", 18 | "typecheck": "tsc --noEmit", 19 | "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", 20 | "test": "jest --clearCache", 21 | "test:watch": "jest --watch", 22 | "test:cov": "jest --coverage", 23 | "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", 24 | "test:e2e": "jest --config ./test/jest-e2e.json", 25 | "db:apply": "prisma db push", 26 | "db:seed": "prisma db seed", 27 | "db:studio": "prisma studio", 28 | "db:migrate": "prisma migrate dev", 29 | "db:migrate:status": "prisma migrate status", 30 | "db:migrate:deploy": "prisma migrate deploy" 31 | }, 32 | "dependencies": { 33 | "@anchan828/nest-i18n-i18next": "^0.3.37", 34 | "@aws-sdk/client-s3": "^3.86.0", 35 | "@nestjs/common": "^8.0.0", 36 | "@nestjs/core": "^8.0.0", 37 | "@nestjs/platform-express": "^8.0.0", 38 | "@nestjs/swagger": "^5.2.1", 39 | "@prisma/client": "^3.13.0", 40 | "i18next": "^21.7.1", 41 | "reflect-metadata": "^0.1.13", 42 | "rimraf": "^3.0.2", 43 | "swagger-ui-express": "^4.3.0", 44 | "zod": "^3.15.1" 45 | }, 46 | "devDependencies": { 47 | "@nestjs/cli": "^8.0.0", 48 | "@nestjs/schematics": "^8.0.0", 49 | "@nestjs/testing": "^8.0.0", 50 | "@types/express": "^4.17.13", 51 | "@types/jest": "27.5.0", 52 | "@types/node": "^16.0.0", 53 | "@types/supertest": "^2.0.11", 54 | "@typescript-eslint/eslint-plugin": "^5.0.0", 55 | "@typescript-eslint/parser": "^5.0.0", 56 | "eslint": "^8.0.1", 57 | "eslint-config-prettier": "^8.3.0", 58 | "eslint-plugin-prettier": "^4.0.0", 59 | "jest": "28.0.3", 60 | "npm-run-all": "^4.1.5", 61 | "prettier": "^2.3.2", 62 | "prisma": "^3.13.0", 63 | "source-map-support": "^0.5.20", 64 | "supertest": "^6.1.3", 65 | "ts-jest": "28.0.1", 66 | "ts-loader": "^9.2.3", 67 | "ts-node": "^10.0.0", 68 | "tsconfig-paths": "4.0.0", 69 | "typescript": "^4.3.5" 70 | }, 71 | "jest": { 72 | "moduleFileExtensions": [ 73 | "js", 74 | "json", 75 | "ts" 76 | ], 77 | "rootDir": "src", 78 | "testRegex": ".*\\.spec\\.ts$", 79 | "transform": { 80 | "^.+\\.(t|j)s$": "ts-jest" 81 | }, 82 | "collectCoverageFrom": [ 83 | "**/*.(t|j)s" 84 | ], 85 | "coverageDirectory": "../coverage", 86 | "testEnvironment": "node" 87 | }, 88 | "prisma": { 89 | "seed": "ts-node prisma/seed.ts" 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /prisma/.env.example: -------------------------------------------------------------------------------- 1 | DATABASE_URL=mysql://root:password@mysql/develop 2 | -------------------------------------------------------------------------------- /prisma/migrations/20220506060138_create_item/migration.sql: -------------------------------------------------------------------------------- 1 | -- CreateTable 2 | CREATE TABLE `Item` ( 3 | `id` INTEGER NOT NULL AUTO_INCREMENT, 4 | `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), 5 | `updatedAt` DATETIME(3) NOT NULL, 6 | `title` VARCHAR(255) NOT NULL, 7 | `content` VARCHAR(191) NULL, 8 | `published` BOOLEAN NOT NULL DEFAULT false, 9 | 10 | PRIMARY KEY (`id`) 11 | ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; 12 | -------------------------------------------------------------------------------- /prisma/migrations/20220508025559_create_account/migration.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Warnings: 3 | 4 | - Added the required column `accountId` to the `Item` table without a default value. This is not possible if the table is not empty. 5 | 6 | */ 7 | -- AlterTable 8 | ALTER TABLE `Item` ADD COLUMN `accountId` INTEGER NOT NULL; 9 | 10 | -- CreateTable 11 | CREATE TABLE `Account` ( 12 | `id` INTEGER NOT NULL AUTO_INCREMENT, 13 | `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), 14 | `updatedAt` DATETIME(3) NOT NULL, 15 | `avatarUrl` VARCHAR(191) NULL, 16 | 17 | PRIMARY KEY (`id`) 18 | ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; 19 | 20 | -- AddForeignKey 21 | ALTER TABLE `Item` ADD CONSTRAINT `Item_accountId_fkey` FOREIGN KEY (`accountId`) REFERENCES `Account`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE; 22 | -------------------------------------------------------------------------------- /prisma/migrations/migration_lock.toml: -------------------------------------------------------------------------------- 1 | # Please do not edit this file manually 2 | # It should be added in your version-control system (i.e. Git) 3 | provider = "mysql" -------------------------------------------------------------------------------- /prisma/schema.prisma: -------------------------------------------------------------------------------- 1 | // This is your Prisma schema file, 2 | // learn more about it in the docs: https://pris.ly/d/prisma-schema 3 | 4 | generator client { 5 | provider = "prisma-client-js" 6 | 7 | // https://github.com/prisma/prisma-client-js/issues/616#issuecomment-616107821 8 | binaryTargets = ["native", "darwin", "debian-openssl-1.1.x"] 9 | } 10 | 11 | model Item { 12 | id Int @id @default(autoincrement()) 13 | createdAt DateTime @default(now()) 14 | updatedAt DateTime @updatedAt 15 | title String @db.VarChar(255) 16 | content String? 17 | published Boolean @default(false) 18 | account Account @relation(fields: [accountId], references: [id]) 19 | accountId Int 20 | } 21 | 22 | model Account { 23 | id Int @id @default(autoincrement()) 24 | createdAt DateTime @default(now()) 25 | updatedAt DateTime @updatedAt 26 | avatarUrl String? 27 | Item Item[] 28 | } 29 | 30 | datasource db { 31 | provider = "mysql" 32 | url = env("DATABASE_URL") 33 | } 34 | -------------------------------------------------------------------------------- /prisma/seed.ts: -------------------------------------------------------------------------------- 1 | import { PrismaClient, PrismaPromise } from '@prisma/client'; 2 | import * as fs from 'fs'; 3 | import * as path from 'path'; 4 | 5 | const prisma = new PrismaClient(); 6 | 7 | const targetDir = path.resolve(__dirname, 'seeds'); 8 | const files = fs.readdirSync(targetDir).filter((f) => f.endsWith('.ts')); 9 | 10 | interface Seed { 11 | default( 12 | prisma: PrismaClient, 13 | ): PrismaPromise | PrismaPromise[]; 14 | } 15 | 16 | async function main() { 17 | console.log(`Start seeding ...`); 18 | 19 | const modules = await Promise.all( 20 | files.map((file) => import(path.resolve(targetDir, file)) as Promise), 21 | ); 22 | 23 | await prisma.$transaction(modules.flatMap((mod) => mod.default(prisma))); 24 | 25 | console.log(`Seeding finished.`); 26 | } 27 | 28 | main(); 29 | -------------------------------------------------------------------------------- /prisma/seeds/01_Item.ts: -------------------------------------------------------------------------------- 1 | import { Prisma, PrismaClient, PrismaPromise } from '@prisma/client'; 2 | 3 | const items: Prisma.ItemCreateInput[] = [ 4 | { 5 | title: 'hoge', 6 | content: 'hello world!!', 7 | account: { 8 | create: { 9 | avatarUrl: 'https://via.placeholder.com/100x100', 10 | }, 11 | }, 12 | }, 13 | ]; 14 | 15 | export default function (prisma: PrismaClient): PrismaPromise[] { 16 | return items.map((item) => 17 | prisma.item.create({ 18 | data: item, 19 | }), 20 | ); 21 | } 22 | -------------------------------------------------------------------------------- /src/app.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { I18nModule } from './i18n/module'; 3 | 4 | import { RootController } from './controllers/root.controller'; 5 | import { ItemController } from './controllers/api/v1/item.controller'; 6 | import { PrismaService } from './services/prisma/prisma.service'; 7 | import { ItemService } from './services/item/item.service'; 8 | 9 | @Module({ 10 | imports: [I18nModule], 11 | controllers: [RootController, ItemController], 12 | providers: [PrismaService, ItemService], 13 | }) 14 | export class AppModule {} 15 | -------------------------------------------------------------------------------- /src/controllers/api/v1/item.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { ItemController } from './item.controller'; 3 | import { ItemService } from '../../../services/item/item.service'; 4 | import { PrismaService } from '../../../services/prisma/prisma.service'; 5 | import { I18nModule } from '../../../i18n/module'; 6 | 7 | describe('ItemController', () => { 8 | let controller: ItemController; 9 | 10 | beforeEach(async () => { 11 | const app: TestingModule = await Test.createTestingModule({ 12 | imports: [I18nModule], 13 | controllers: [ItemController], 14 | providers: [ItemService, PrismaService], 15 | }).compile(); 16 | 17 | controller = app.get(ItemController); 18 | }); 19 | 20 | describe('index', () => { 21 | it('should return', async () => { 22 | const response = await controller.index(); 23 | 24 | expect(response).toBeInstanceOf(Array); 25 | }); 26 | }); 27 | }); 28 | -------------------------------------------------------------------------------- /src/controllers/api/v1/item.controller.ts: -------------------------------------------------------------------------------- 1 | import { 2 | I18nExceptionFilter, 3 | I18nNotFoundException, 4 | } from '@anchan828/nest-i18n-i18next'; 5 | import { 6 | Controller, 7 | Get, 8 | Param, 9 | ParseIntPipe, 10 | UseFilters, 11 | } from '@nestjs/common'; 12 | import { ApiNotFoundResponse, ApiOkResponse } from '@nestjs/swagger'; 13 | import { ItemDto } from '../../../services/item/item.dto'; 14 | import { ItemService } from '../../../services/item/item.service'; 15 | 16 | @Controller('api/v1/items') 17 | @UseFilters(I18nExceptionFilter) 18 | export class ItemController { 19 | constructor(private readonly items: ItemService) {} 20 | 21 | @Get('/') 22 | @ApiOkResponse({ type: [ItemDto] }) 23 | async index() { 24 | const items = await this.items.findAll(); 25 | 26 | return items; 27 | } 28 | 29 | @Get(':id') 30 | @ApiNotFoundResponse() 31 | @ApiOkResponse({ type: ItemDto }) 32 | async show(@Param('id', ParseIntPipe) id: number) { 33 | const item = await this.items.findById(id); 34 | 35 | if (!item) { 36 | throw new I18nNotFoundException({ 37 | key: 'requests.not_found', 38 | options: {}, 39 | }); 40 | } 41 | 42 | return item; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/controllers/root.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { RootController } from './root.controller'; 3 | import { ItemService } from '../services/item/item.service'; 4 | import { PrismaService } from '../services/prisma/prisma.service'; 5 | 6 | describe('RootController', () => { 7 | let controller: RootController; 8 | 9 | beforeEach(async () => { 10 | const app: TestingModule = await Test.createTestingModule({ 11 | controllers: [RootController], 12 | providers: [ItemService, PrismaService], 13 | }).compile(); 14 | 15 | controller = app.get(RootController); 16 | }); 17 | 18 | describe('root', () => { 19 | it('should return', async () => { 20 | expect(await controller.index()).toEqual({ healthz: true }); 21 | }); 22 | }); 23 | }); 24 | -------------------------------------------------------------------------------- /src/controllers/root.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller, Get } from '@nestjs/common'; 2 | 3 | @Controller() 4 | export class RootController { 5 | @Get('/') 6 | async index() { 7 | return { healthz: true }; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/i18n/en.json: -------------------------------------------------------------------------------- 1 | { 2 | "translation": { 3 | "requests": { 4 | "not_found": "Record was not found", 5 | "bad_request": "Invalid Request" 6 | }, 7 | "items": { 8 | "invalid_updated_at": "updatedAt must be later than or equals createdAt" 9 | } 10 | } 11 | } -------------------------------------------------------------------------------- /src/i18n/ja.json: -------------------------------------------------------------------------------- 1 | { 2 | "translation": { 3 | "requests": { 4 | "not_found": "レコードが見つかりません", 5 | "bad_request": "不正なリクエストです" 6 | }, 7 | "items": { 8 | "invalid_updated_at": "updatedAt は createdAt 以降でなければなりません" 9 | } 10 | } 11 | } -------------------------------------------------------------------------------- /src/i18n/module.ts: -------------------------------------------------------------------------------- 1 | import { I18nextModule } from '@anchan828/nest-i18n-i18next'; 2 | import { DEFAULT_LOCALE, Locales } from './utils'; 3 | 4 | import * as en from './en.json'; 5 | import * as ja from './ja.json'; 6 | 7 | const resources: Record = { 8 | 'en-US': en, 9 | 'ja-JP': ja, 10 | }; 11 | 12 | export const I18nModule = I18nextModule.register({ 13 | fallbackLng: [DEFAULT_LOCALE], 14 | resources, 15 | }); 16 | -------------------------------------------------------------------------------- /src/i18n/utils.ts: -------------------------------------------------------------------------------- 1 | import z from 'zod'; 2 | 3 | export const LOCALES = z.enum(['ja-JP', 'en-US']); 4 | 5 | export type Locales = z.infer; 6 | 7 | export const DEFAULT_LOCALE: Locales = 'ja-JP'; 8 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { INestApplication } from '@nestjs/common'; 2 | import { NestFactory } from '@nestjs/core'; 3 | import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; 4 | import { AppModule } from './app.module'; 5 | import { PrismaService } from './services/prisma/prisma.service'; 6 | 7 | async function bootstrap() { 8 | const app = await NestFactory.create(AppModule); 9 | bootstrapSwagger(app); 10 | 11 | const prismaService = app.get(PrismaService); 12 | await prismaService.enableShutdownHooks(app); 13 | 14 | await app.listen(3000); 15 | } 16 | 17 | bootstrap(); 18 | 19 | function bootstrapSwagger(app: INestApplication) { 20 | const config = new DocumentBuilder() 21 | .setTitle('Example API') 22 | .setDescription('The Example API description') 23 | .setVersion('1.0') 24 | .addTag('example') 25 | .build(); 26 | 27 | const document = SwaggerModule.createDocument(app, config); 28 | 29 | SwaggerModule.setup('api', app, document); 30 | } 31 | -------------------------------------------------------------------------------- /src/services/item/item.dto.ts: -------------------------------------------------------------------------------- 1 | import { Item } from '@prisma/client'; 2 | 3 | export class ItemDto { 4 | id: number; 5 | content: string | null; 6 | updatedAt: Date; 7 | createdAt: Date; 8 | 9 | constructor({ id, content, updatedAt, createdAt }: Item) { 10 | this.id = id; 11 | this.content = content; 12 | this.updatedAt = updatedAt; 13 | this.createdAt = createdAt; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/services/item/item.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { PrismaService } from '../prisma/prisma.service'; 3 | import { ItemService } from './item.service'; 4 | 5 | describe('ItemService', () => { 6 | let service: ItemService; 7 | 8 | beforeEach(async () => { 9 | const module: TestingModule = await Test.createTestingModule({ 10 | providers: [ItemService, PrismaService], 11 | }).compile(); 12 | 13 | service = module.get(ItemService); 14 | }); 15 | 16 | it('should be defined', () => { 17 | expect(service).toBeDefined(); 18 | }); 19 | }); 20 | -------------------------------------------------------------------------------- /src/services/item/item.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { PrismaService } from '../prisma/prisma.service'; 3 | import { ItemDto } from './item.dto'; 4 | 5 | @Injectable() 6 | export class ItemService { 7 | constructor(private prisma: PrismaService) {} 8 | 9 | async findAll() { 10 | const items = await this.prisma.item.findMany(); 11 | 12 | return items.map((item) => new ItemDto(item)); 13 | } 14 | 15 | async findById(id: number) { 16 | const item = await this.prisma.item.findFirst({ 17 | where: { id }, 18 | }); 19 | 20 | if (!item) { 21 | return null; 22 | } 23 | 24 | return new ItemDto(item); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/services/prisma/prisma.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { PrismaService } from './prisma.service'; 3 | 4 | describe('PrismaService', () => { 5 | let service: PrismaService; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ 9 | providers: [PrismaService], 10 | }).compile(); 11 | 12 | service = module.get(PrismaService); 13 | }); 14 | 15 | it('should be defined', () => { 16 | expect(service).toBeDefined(); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /src/services/prisma/prisma.service.ts: -------------------------------------------------------------------------------- 1 | import { INestApplication, Injectable, OnModuleInit } from '@nestjs/common'; 2 | import { PrismaClient } from '@prisma/client'; 3 | 4 | @Injectable() 5 | export class PrismaService extends PrismaClient implements OnModuleInit { 6 | async onModuleInit() { 7 | await this.$connect(); 8 | } 9 | 10 | async enableShutdownHooks(app: INestApplication) { 11 | this.$on('beforeExit', async () => { 12 | await app.close(); 13 | }); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /test/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { INestApplication } from '@nestjs/common'; 3 | import * as request from 'supertest'; 4 | import { AppModule } from './../src/app.module'; 5 | 6 | describe('AppController (e2e)', () => { 7 | let app: INestApplication; 8 | 9 | beforeEach(async () => { 10 | const moduleFixture: TestingModule = await Test.createTestingModule({ 11 | imports: [AppModule], 12 | }).compile(); 13 | 14 | app = moduleFixture.createNestApplication(); 15 | await app.init(); 16 | }); 17 | 18 | it('/ (GET)', () => { 19 | return request(app.getHttpServer()).get('/').expect(200); 20 | }); 21 | }); 22 | -------------------------------------------------------------------------------- /test/jest-e2e.json: -------------------------------------------------------------------------------- 1 | { 2 | "moduleFileExtensions": ["js", "json", "ts"], 3 | "rootDir": ".", 4 | "testEnvironment": "node", 5 | "testRegex": ".e2e-spec.ts$", 6 | "transform": { 7 | "^.+\\.(t|j)s$": "ts-jest" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "exclude": ["node_modules", "test", "dist", "**/*spec.ts"] 4 | } 5 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "declaration": true, 5 | "removeComments": true, 6 | "emitDecoratorMetadata": true, 7 | "experimentalDecorators": true, 8 | "allowSyntheticDefaultImports": true, 9 | "resolveJsonModule": true, 10 | "target": "esnext", 11 | "sourceMap": true, 12 | "outDir": "./dist", 13 | "baseUrl": "./", 14 | "incremental": true, 15 | "skipLibCheck": true, 16 | "strict": true 17 | } 18 | } 19 | --------------------------------------------------------------------------------