Skip to content

Commit

Permalink
introduce prisma&psql
Browse files Browse the repository at this point in the history
  • Loading branch information
mk668a committed Jul 12, 2022
1 parent 46f1289 commit 952adb8
Show file tree
Hide file tree
Showing 19 changed files with 1,033 additions and 102 deletions.
1 change: 1 addition & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DATABASE_URL="postgresql://mk:mk@localhost:5432/postgres?schema=public"
1 change: 1 addition & 0 deletions .env.development
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

1 change: 1 addition & 0 deletions .env.production
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

1 change: 1 addition & 0 deletions .env.staging
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

12 changes: 2 additions & 10 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ module.exports = {
], // asで型付けを禁止(type assertion禁止)
'@typescript-eslint/consistent-type-definitions': ['error', 'type'], // interface禁止、typeのみ使用可
'@typescript-eslint/dot-notation': ['error'], // objectのkeyを指定する時、できるだけドットを使用する
'@typescript-eslint/explicit-module-boundary-types': ['error'], // 関数の返り値の型と、関数内のreturnの型を一致させる
'@typescript-eslint/lines-between-class-members': ['error'], // classのメンバに改行を強制
'@typescript-eslint/member-ordering': ['error', { default: ['constructor', 'field', 'signature', 'method'] }], // classのメンバの宣言順を強制
'@typescript-eslint/method-signature-style': ['error', 'property'], // functionの型をアロー関数で書く: func(arg: boolean): void -> func: (arg: boolean) => void
Expand All @@ -38,13 +37,13 @@ module.exports = {
'@typescript-eslint/no-namespace': 'error', // namespace使用禁止
'@typescript-eslint/no-shadow': ['error'], // スコープ外に存在する変数と同じ名前の変数を宣言するとエラー
'@typescript-eslint/no-unnecessary-boolean-literal-compare': 'error', // boolean型の不要な比較を禁止(if(bool === true)など)
'@typescript-eslint/no-unnecessary-condition': 'error', // 不要なif文を禁止
'@typescript-eslint/no-unnecessary-condition': 'warn', // 不要なif文を禁止
'@typescript-eslint/no-unused-vars': 'off',
'@typescript-eslint/no-var-requires': 'off',
'@typescript-eslint/prefer-for-of': 'error', // for(let i... でiを使用してない場合は for of を使うように強制
'@typescript-eslint/prefer-includes': 'error', // indexOf使用禁止: includesを使う
'@typescript-eslint/prefer-string-starts-ends-with': 'error', // 文字列が特定の文字列で開始するか終了するかを確認する時、startsWith/endsWithの使用を強制
'@typescript-eslint/strict-boolean-expressions': 'error', // booleanが予想されるif文での非booleanの使用を禁止する
'@typescript-eslint/strict-boolean-expressions': 'warn', // booleanが予想されるif文での非booleanの使用を禁止する
'@typescript-eslint/typedef': [
'error',
{
Expand All @@ -63,13 +62,6 @@ module.exports = {
'no-mixed-spaces-and-tabs': 'error', // インデントにタブと空白を混在させないこと
'no-nested-ternary': 'error', // 3項演算子をネストさせないこと
'no-proto': 'error', // __proto__ を使用しないこと
'no-restricted-syntax': [
'error',
{
selector: 'TSEnumDeclaration',
message: "Don't use `enum` as a type."
}
], // enum禁止
'no-trailing-spaces': 'error', // 行末に不要な空白を残さないこと
'no-useless-concat': 'error', // 無駄な文字列結合は行わないこと
'object-shorthand': 'error', // オブジェクト定義時にショートハンドが利用できる場合は利用すること
Expand Down
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,4 @@ lerna-debug.log*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
!.vscode/extensions.json
5 changes: 4 additions & 1 deletion nest-cli.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src"
"sourceRoot": "src",
"compilerOptions": {
"plugins": ["@nestjs/graphql"]
}
}
11 changes: 8 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"format": "yarn lint && prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start:dev": "NODE_ENV=development && nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "NODE_ENV=production && node dist/main",
Expand All @@ -18,18 +17,21 @@
"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"
"test:e2e": "jest --config ./test/jest-e2e.json",
"generate": "prisma generate && yarn format"
},
"dependencies": {
"@nestjs/apollo": "^10.0.17",
"@nestjs/common": "^9.0.0",
"@nestjs/core": "^9.0.0",
"@nestjs/graphql": "^10.0.18",
"@nestjs/platform-express": "^9.0.0",
"@prisma/client": "^4.0.0",
"apollo-server-express": "^3.9.0",
"dayjs": "^1.11.3",
"graphql": "^16.5.0",
"lint-staged": "^13.0.3",
"prisma": "^4.0.0",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^7.2.0"
Expand All @@ -46,7 +48,9 @@
"@typescript-eslint/parser": "^5.0.0",
"eslint": "^8.0.1",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-jest": "^26.5.3",
"eslint-plugin-prettier": "^4.0.0",
"eslint-plugin-unused-imports": "^2.0.0",
"jest": "28.1.2",
"prettier": "^2.3.2",
"source-map-support": "^0.5.20",
Expand All @@ -55,6 +59,7 @@
"ts-loader": "^9.2.3",
"ts-node": "^10.0.0",
"tsconfig-paths": "4.0.0",
"typegraphql-prisma": "^0.21.0",
"typescript": "^4.3.5"
},
"jest": {
Expand Down
11 changes: 11 additions & 0 deletions prisma/migrations/20220712051537_init/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
-- CreateTable
CREATE TABLE "Users" (
"id" SERIAL NOT NULL,
"first_name" TEXT NOT NULL,
"last_name" TEXT NOT NULL,
"gender" TEXT,
"created_at" TEXT NOT NULL,
"updated_at" TEXT NOT NULL,

CONSTRAINT "Users_pkey" PRIMARY KEY ("id")
);
3 changes: 3 additions & 0 deletions prisma/migrations/migration_lock.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (i.e. Git)
provider = "postgresql"
20 changes: 20 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
provider = "prisma-client-js"
}

datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}

model Users {
id Int @default(autoincrement()) @id
first_name String
last_name String
gender String?
created_at String
updated_at String
}
8 changes: 6 additions & 2 deletions schema.gql
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ A date-time string at UTC, such as 2019-12-03T09:54:33Z, compliant with the date
scalar DateTime

type Query {
findAll: [Users]!
findOneById(id: ID!): Users!
users: [Users!]
user(id: ID!): Users
}

type Mutation {
createUser(firstName: String!, lastName: String!): Users
}
15 changes: 15 additions & 0 deletions src/prisma.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { INestApplication, Injectable, OnModuleInit } from '@nestjs/common'
import { PrismaClient } from '@prisma/client'

@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit {
async onModuleInit() {
await this.$connect()
}

async enableShutdownHooks(app: INestApplication) {
this.$on('beforeExit', async () => {
await app.close()
})
}
}
6 changes: 3 additions & 3 deletions src/users/users.models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ registerEnumType(Status, {

@ObjectType()
export class Users {
@Field((type) => ID)
@Field(() => ID)
id: string

@Field()
Expand All @@ -21,9 +21,9 @@ export class Users {
lastName: string

@Field({ nullable: true })
gender: string
gender?: string

@Field((type) => Status)
@Field(() => Status)
status: Status

@Field()
Expand Down
3 changes: 2 additions & 1 deletion src/users/users.module.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { Module } from '@nestjs/common'
import { UsersService } from './users.service'
import { UsersResolver } from './users.resolver'
import { PrismaService } from 'src/prisma.service'

@Module({
providers: [UsersService, UsersResolver]
providers: [UsersService, UsersResolver, PrismaService]
})
export class UsersModule {}
17 changes: 11 additions & 6 deletions src/users/users.resolver.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,23 @@
import { Args, ID, Query, Resolver } from '@nestjs/graphql'
import { Args, ID, Mutation, Query, Resolver } from '@nestjs/graphql'
import { Users } from './users.models'
import { UsersService } from './users.service'

@Resolver()
@Resolver((of) => Users)
export class UsersResolver {
constructor(private usersService: UsersService) {}

@Query(() => [Users], { nullable: 'items' })
findAll() {
@Query(() => [Users], { nullable: true })
users() {
return this.usersService.findAll()
}

@Query(() => Users)
findOneById(@Args('id', { type: () => ID }) id: string) {
@Query(() => Users, { nullable: true })
user(@Args('id', { type: () => ID }) id: string) {
return this.usersService.findOneById(id)
}

@Mutation(() => Users, { nullable: true })
async createUser(@Args('firstName') firstName: string, @Args('lastName') lastName: string) {
return this.usersService.create(firstName, lastName)
}
}
24 changes: 12 additions & 12 deletions src/users/users.service.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
import { Injectable, NotFoundException } from '@nestjs/common'
import { Status, Users } from './users.models'
import { Injectable } from '@nestjs/common'
import dayjs from 'dayjs'
import { PrismaService } from 'src/prisma.service'

@Injectable()
export class UsersService {
private users: Users[] = [
{ id: '1', gender: '', firstName: 'aaa', lastName: 'bbb', status: Status.ACTIVE, createdAt: new Date(), updatedAt: new Date() },
{ id: '2', gender: '', firstName: 'aaa2', lastName: 'bbb2', status: Status.ACTIVE, createdAt: new Date(), updatedAt: new Date() }
]
constructor(private prisma: PrismaService) {}

findAll(): Users[] {
return this.users
async findAll() {
return await this.prisma.users.findMany()
}

findOneById(id: string): Users {
const result = this.users.find((todo) => id === todo.id)
if (!result) throw new NotFoundException()
return result
async findOneById(id: string) {
return await this.prisma.users.findUnique({ where: { id: Number(id) } })
}

async create(firstName: string, lastName: string) {
return this.prisma.users.create({ data: { first_name: firstName, last_name: lastName, created_at: dayjs().toString(), updated_at: dayjs().toString() } })
}
}
6 changes: 4 additions & 2 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "es2017",
"target": "es2018",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
Expand All @@ -16,6 +16,8 @@
"noImplicitAny": false,
"strictBindCallApply": false,
"forceConsistentCasingInFileNames": false,
"noFallthroughCasesInSwitch": false
"noFallthroughCasesInSwitch": false,
"lib": ["es2018", "esnext.asynciterable"],
"esModuleInterop": true
}
}
Loading

0 comments on commit 952adb8

Please sign in to comment.