初始化

This commit is contained in:
ZtRXR 2023-09-01 20:23:50 +08:00
parent 0561197b1c
commit fddddd68fd
10 changed files with 1688 additions and 132 deletions

136
.gitignore vendored
View File

@ -1,132 +1,6 @@
# ---> Node .idea/
# Logs .vscode/
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/ node_modules/
jspm_packages/ build/
tmp/
# Snowpack dependency directory (https://snowpack.dev/) temp/
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
.cache
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*

View File

@ -1,2 +1,7 @@
# DataBack # Awesome Project Build with TypeORM
Steps to run this project:
1. Run `npm i` command
2. Setup database settings inside `data-source.ts` file
3. Run `npm start` command

1477
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

22
package.json Normal file
View File

@ -0,0 +1,22 @@
{
"name": "typeorm-sample",
"version": "0.0.1",
"description": "Awesome project developed with TypeORM.",
"type": "commonjs",
"devDependencies": {
"ts-node": "10.7.0",
"@types/node": "^16.11.10",
"typescript": "4.5.2"
},
"dependencies": {
"typeorm": "0.3.17",
"reflect-metadata": "^0.1.13",
"mysql": "^2.14.1",
"express": "^4.17.2",
"body-parser": "^1.19.1"
},
"scripts": {
"start": "ts-node src/index.ts",
"typeorm": "typeorm-ts-node-commonjs"
}
}

View File

@ -0,0 +1,53 @@
import { AppDataSource } from "../data-source"
import { NextFunction, Request, Response } from "express"
import { User } from "../entity/User"
export class UserController {
private userRepository = AppDataSource.getRepository(User)
async all(request: Request, response: Response, next: NextFunction) {
return this.userRepository.find()
}
async one(request: Request, response: Response, next: NextFunction) {
const id = parseInt(request.params.id)
const user = await this.userRepository.findOne({
where: { id }
})
if (!user) {
return "unregistered user"
}
return user
}
async save(request: Request, response: Response, next: NextFunction) {
const { firstName, lastName, age } = request.body;
const user = Object.assign(new User(), {
firstName,
lastName,
age
})
return this.userRepository.save(user)
}
async remove(request: Request, response: Response, next: NextFunction) {
const id = parseInt(request.params.id)
let userToRemove = await this.userRepository.findOneBy({ id })
if (!userToRemove) {
return "this user not exist"
}
await this.userRepository.remove(userToRemove)
return "user has been removed"
}
}

17
src/data-source.ts Normal file
View File

@ -0,0 +1,17 @@
import "reflect-metadata"
import { DataSource } from "typeorm"
import { User } from "./entity/User"
export const AppDataSource = new DataSource({
type: "mysql",
host: "localhost",
port: 3306,
username: "test",
password: "test",
database: "test",
synchronize: true,
logging: false,
entities: [User],
migrations: [],
subscribers: [],
})

18
src/entity/User.ts Normal file
View File

@ -0,0 +1,18 @@
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column()
firstName: string
@Column()
lastName: string
@Column()
age: number
}

52
src/index.ts Normal file
View File

@ -0,0 +1,52 @@
import * as express from "express"
import * as bodyParser from "body-parser"
import { Request, Response } from "express"
import { AppDataSource } from "./data-source"
import { Routes } from "./routes"
import { User } from "./entity/User"
AppDataSource.initialize().then(async () => {
// create express app
const app = express()
app.use(bodyParser.json())
// register express routes from defined application routes
Routes.forEach(route => {
(app as any)[route.method](route.route, (req: Request, res: Response, next: Function) => {
const result = (new (route.controller as any))[route.action](req, res, next)
if (result instanceof Promise) {
result.then(result => result !== null && result !== undefined ? res.send(result) : undefined)
} else if (result !== null && result !== undefined) {
res.json(result)
}
})
})
// setup express app here
// ...
// start express server
app.listen(3000)
// insert new users for test
await AppDataSource.manager.save(
AppDataSource.manager.create(User, {
firstName: "Timber",
lastName: "Saw",
age: 27
})
)
await AppDataSource.manager.save(
AppDataSource.manager.create(User, {
firstName: "Phantom",
lastName: "Assassin",
age: 24
})
)
console.log("Express server has started on port 3000. Open http://localhost:3000/users to see results")
}).catch(error => console.log(error))

23
src/routes.ts Normal file
View File

@ -0,0 +1,23 @@
import { UserController } from "./controller/UserController"
export const Routes = [{
method: "get",
route: "/users",
controller: UserController,
action: "all"
}, {
method: "get",
route: "/users/:id",
controller: UserController,
action: "one"
}, {
method: "post",
route: "/users",
controller: UserController,
action: "save"
}, {
method: "delete",
route: "/users/:id",
controller: UserController,
action: "remove"
}]

15
tsconfig.json Normal file
View File

@ -0,0 +1,15 @@
{
"compilerOptions": {
"lib": [
"es5",
"es6"
],
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"outDir": "./build",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"sourceMap": true
}
}