Skip to content

Commit 93054e9

Browse files
committed
typeORMの導入、GETAPIでDBのデータを取得
1 parent c82693b commit 93054e9

14 files changed

+552
-22
lines changed

.gitignore

+2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
volumes
2+
13
# Logs
24
logs
35
*.log

README.md

+21-1
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,24 @@ yarn
1515
起動
1616
```
1717
yarn start
18-
```
18+
```
19+
20+
2. method
21+
インストール
22+
```
23+
cd samples/method
24+
yarn
25+
```
26+
27+
DB起動
28+
```
29+
// samplesディレクトリに移動
30+
cd ../
31+
docker-compose up -d
32+
```
33+
34+
起動
35+
```
36+
cd samples/method
37+
yarn start
38+
```

samples/docker-compose.yml

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Use root/example as user/password credentials
2+
version: '3.1'
3+
4+
services:
5+
6+
db:
7+
image: mysql
8+
command: --default-authentication-plugin=mysql_native_password
9+
restart: always
10+
ports:
11+
- 13306:3306
12+
volumes:
13+
- ./volumes/example_db/db/data:/var/lib/mysql
14+
- ./volumes/example_db/db/my.cnf:/etc/mysql/conf.d/my.cnf
15+
environment:
16+
MYSQL_DATABASE: example_db
17+
MYSQL_ROOT_PASSWORD: example
18+
MYSQL_USER: docker
19+
MYSQL_PASSWORD: docker
20+
21+
adminer:
22+
image: adminer
23+
restart: always
24+
ports:
25+
- 8080:8080

samples/hello-world/src/index.ts

+1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import express from 'express'
2+
import "reflect-metadata"
23

34
const app: express.Express = express()
45

samples/method/data-source.ts

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { DataSource } from "typeorm";
2+
3+
const AppDataSource = new DataSource({
4+
type: "mysql",
5+
host: "localhost",
6+
port: 13306,
7+
username: "docker",
8+
password: "docker",
9+
database: "example_db",
10+
synchronize: false,
11+
logging: true,
12+
entities: ["src/entities/**/*.ts"],
13+
migrations: ["src/migrations/**/*.ts"],
14+
})
15+
16+
export default AppDataSource

samples/method/docs/reference/tutorial-api.yaml

+2-2
Original file line numberDiff line numberDiff line change
@@ -44,11 +44,11 @@ paths:
4444
$ref: '#/components/schemas/Content'
4545
tags:
4646
- Content
47-
'/contents/{contentsId}':
47+
'/contents/{contentId}':
4848
parameters:
4949
- schema:
5050
type: string
51-
name: contentsId
51+
name: contentId
5252
in: path
5353
required: true
5454
get:

samples/method/nodemon.json

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{
2+
"watch": [
3+
"src"
4+
],
5+
"ext": "ts",
6+
"exec": "ts-node -r tsconfig-paths/register ./src/index.ts"
7+
}

samples/method/package.json

+9-2
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,22 @@
44
"main": "index.js",
55
"license": "MIT",
66
"scripts": {
7+
"dev": "./node_modules/.bin/nodemon",
78
"start": "ts-node src/index.ts",
89
"lint": "eslint --fix './src/**/*.{js,jsx,ts,tsx}'",
9-
"format": "prettier --write ./src"
10+
"format": "prettier --write ./src",
11+
"make:migration": "typeorm-ts-node-commonjs migration:generate ./src/migrations -d ./data-source.ts",
12+
"migrate": "typeorm-ts-node-commonjs migration:run -d ./data-source.ts",
13+
"rollback": "typeorm-ts-node-commonjs migration:revert -d ./data-source.ts"
1014
},
1115
"dependencies": {
1216
"@typescript-eslint/eslint-plugin": "^5.32.0",
1317
"@typescript-eslint/parser": "^5.32.0",
1418
"eslint": "^7.32.0 || ^8.2.0",
15-
"express": "^4.18.1"
19+
"express": "^4.18.1",
20+
"nodemon": "^2.0.19",
21+
"reflect-metadata": "^0.1.13",
22+
"typeorm": "^0.3.7"
1623
},
1724
"devDependencies": {
1825
"@types/express": "^4.17.13",
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
CREATE TABLE `content` (
2+
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
3+
title VARCHAR(256),
4+
body VARCHAR(1024)) ENGINE = InnoDB;
+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm'
2+
3+
@Entity()
4+
export class Content {
5+
@PrimaryGeneratedColumn()
6+
id!: number
7+
8+
@Column('varchar')
9+
title: string
10+
11+
@Column('varchar')
12+
body: string
13+
14+
constructor(title: string, body: string) {
15+
this.title = title
16+
this.body = body
17+
}
18+
}

samples/method/src/index.ts

+21-4
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import express from 'express'
2-
import { contents } from './constants'
2+
import AppDataSource from '../data-source'
3+
import { Content } from './entities/Content'
34

45
const app: express.Express = express()
56

@@ -14,13 +15,29 @@ app.use((req, res, next) => {
1415
app.use(express.json())
1516
app.use(express.urlencoded({ extended: true }))
1617

17-
// Get /contents
18+
AppDataSource.initialize()
19+
1820
const router: express.Router = express.Router()
19-
router.get('/contents', (req: express.Request, res: express.Response) => {
21+
22+
const repository = AppDataSource.getRepository(Content)
23+
24+
// GET /contents
25+
router.get('/contents', async (req: express.Request, res: express.Response) => {
26+
const contents = await repository.find()
2027
res.send(contents)
2128
})
22-
app.use(router)
2329

30+
// GET /contents/:id
31+
router.get('/contents/:id', async (req: express.Request, res: express.Response) => {
32+
const content = await repository.findOne({
33+
where: { id: Number(req.params.id) },
34+
order: { id: 'ASC' },
35+
})
36+
if (content == null) res.status(404).send()
37+
res.send(content)
38+
})
39+
40+
app.use(router)
2441
// 3000番ポートでAPIサーバ起動
2542
app.listen(3000, () => {
2643
console.log('Example app listening on port 3000!')
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { MigrationInterface, QueryRunner } from 'typeorm'
2+
3+
export class migrations1659710150627 implements MigrationInterface {
4+
name = 'migrations1659710150627'
5+
6+
public async up(queryRunner: QueryRunner): Promise<void> {
7+
await queryRunner.query(
8+
`CREATE TABLE \`content\` (\`id\` int NOT NULL AUTO_INCREMENT, \`title\` varchar(255) NOT NULL, \`body\` varchar(255) NOT NULL, PRIMARY KEY (\`id\`)) ENGINE=InnoDB`
9+
)
10+
}
11+
12+
public async down(queryRunner: QueryRunner): Promise<void> {
13+
await queryRunner.query(`DROP TABLE \`content\``)
14+
}
15+
}

samples/method/tsconfig.json

+2-2
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@
1414
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
1515
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
1616
// "jsx": "preserve", /* Specify what JSX code is generated. */
17-
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
18-
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
17+
"experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
18+
"emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
1919
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
2020
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
2121
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */

0 commit comments

Comments
 (0)