Skip to content

Commit

Permalink
chore: Add express-typeorm example.
Browse files Browse the repository at this point in the history
  • Loading branch information
jaywcjlove committed Feb 2, 2021
1 parent 9d75634 commit 76718f3
Show file tree
Hide file tree
Showing 24 changed files with 741 additions and 0 deletions.
38 changes: 38 additions & 0 deletions example/express-typeorm/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# we try to aoid adding files to the docker images that change often
# or that are not needed for running the docker image
# tis greatly reduces the amount of times we need to rerun `npm install` when building image locally
# https://codefresh.io/blog/not-ignore-dockerignore/
# https://docs.docker.com/engine/reference/builder/#dockerignore-file

# consider them hidden
.*
# you can add exceptions like in .gitignore to maintain a whitelist:
# e.g.
!.babelrc
!.eslintrc
!.eslintignore
!.stylelintrc
!.flowconfig
!.jest.config.js
!.jestEnvironment.js

# do not copy over node_modules we will run `npm install` anyway
node_modules

# output from test runs and similar things
*.log
*.pid
log
coverage/
dump.rdb
.vscode/
.git
*.log

# IDE config files
jsconfig.json
*.iml

# let's not get to recursive ;)
Dockerfile*
docker-compose*.yaml
114 changes: 114 additions & 0 deletions example/express-typeorm/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
# Created by https://www.gitignore.io/api/node
# Edit at https://www.gitignore.io/?templates=node

lib
package-lock.json
__snapshots__
*.sqlite

### Node ###
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-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

# 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/
jspm_packages/

# TypeScript v1 declaration files
typings/

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env
.env.test

# parcel-bundler cache (https://parceljs.org/)
.cache

# next.js build output
.next

# nuxt.js build output
.nuxt

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# End of https://www.gitignore.io/api/node

.DS_Store
.cache
.vscode
.idea
.env

*.bak
*.tem
*.temp
#.swp
*.*~
~*.*

# IDEA
*.iml
*.ipr
*.iws
.idea/
15 changes: 15 additions & 0 deletions example/express-typeorm/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
FROM node:12

ENV APPDIR /opt/app

RUN mkdir -p $APPDIR
ADD . $APPDIR

COPY package.json package-lock.json* ./
#RUN npm install --only=production && npm cache clean --force
RUN npm install --registry=https://registry.npm.taobao.org && npm cache clean --force
ENV PATH /opt/node_modules/.bin:$PATH

WORKDIR $APPDIR
CMD [ "node", "/opt/app/lib/main.js" ]
EXPOSE 3009
20 changes: 20 additions & 0 deletions example/express-typeorm/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
## Terminal Server

```shell
$ npm install

npm run watch # Listen compile .ts files.
npm run build # compile .ts files.
```

Production mode starts the service.

```bash
npm run start
```

Automatically restarting the node application when file changes in the directory are detected.

```bash
npm run dev
```
21 changes: 21 additions & 0 deletions example/express-typeorm/api-test/user-account.http
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@


@baseUrl = http://localhost:3009/api
@contentType = application/json


### 用户登录

# @name login
POST {{baseUrl}}/login
Content-Type: {{contentType}}

{
"username": "admin",
"password": "123456"
}

### User Verify

GET {{baseUrl}}/verify
Content-Type: application/json
Empty file.
55 changes: 55 additions & 0 deletions example/express-typeorm/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
{
"name": "@template/express-typeorm",
"version": "2.0.7",
"private": true,
"description": "Express Typeorm Example.",
"scripts": {
"start": "npm run build && node lib/main.js",
"tsdev": "ts-node-dev --respawn --transpile-only src/main.ts",
"dev": "npm run build && nodemon --inspect lib/main.js",
"types": "tsbb types",
"types:watch": "tsbb types --watch",
"watch": "tsbb watch",
"build": "tsbb build",
"test": "tsbb test",
"coverage": "tsbb test --coverage"
},
"author": "jaywcjlove",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/jaywcjlove/tsbb/tree/master/example/express"
},
"nodemonConfig": {
"ignore": [
"test/*",
"node_modules/*"
],
"delay": "2500"
},
"devDependencies": {
"@types/compression": "1.7.0",
"@types/cookie-parser": "1.4.2",
"@types/express": "4.17.6",
"@types/node": "14.14.22",
"@types/express-session": "1.17.3",
"@types/http-errors": "1.8.0",
"nodemon": "2.0.7",
"ts-node": "9.1.1",
"ts-node-dev": "1.1.1",
"tsbb": "2.0.7"
},
"dependencies": {
"@babel/runtime": "7.12.5",
"compression": "1.7.4",
"cookie-parser": "1.4.5",
"ejs": "3.1.5",
"express": "4.17.1",
"express-session": "1.17.1",
"http-errors": "1.8.0",
"reflect-metadata": "0.1.13",
"sqlite3": "5.0.1",
"typeorm": "0.2.30",
"typeorm-store": "1.2.0"
}
}
89 changes: 89 additions & 0 deletions example/express-typeorm/src/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/// <reference path="./types/global.d.ts" />

import path from 'path';
import compression from 'compression';
import createError from 'http-errors';
import cookieParser from 'cookie-parser';
import express, { Express, Response, Request, NextFunction } from 'express';
import routes from './routes/index';
import { Routes } from './routes';
import { createSession } from './utils/session';

export async function expressApp(): Promise<Express> {
const app: Express = express();
app.use(createSession());
app.disable('x-powered-by');
app.set('port', process.env.PORT || 3009);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(compression());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public'), { maxAge: 31557600000 }));

// register express routes from defined application routes
Routes.forEach((route) => {
app[route.method](route.route, (req: Request, res: Response, next: NextFunction) => {
const result = new route.controller()[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);
}
});
});

// app.get('/', (req: Request, res: Response) => {
// res.send('Hello World');
// });
routes(app);

// catch 404 and forward to error handler
app.use((req: Request, res: Response, next: NextFunction) => {
next(createError(404));
});

// error handler
app.use((err: any, req: Request, res: Response, next: NextFunction) => {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});

app.listen(app.get('port'), () => {
console.log(
'\n App is running at\x1b[32;1m http://localhost:%d\x1b[0m in %s mode',
app.get('port'),
app.get('env'),
);
console.log(' Press\x1b[33;1m CTRL-C\x1b[0m to stop\n');
});

/**
* Event listener for HTTP server "error" event.
*/
app.on('error', (error: any) => {
if (error.syscall !== 'listen') {
throw error;
}
const bind = typeof app.get('port') === 'string' ? 'Pipe ' + app.get('port') : 'Port ' + app.get('port');
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(`${bind} requires elevated privileges`);
process.exit(1);
break;
case 'EADDRINUSE':
console.error(`${bind} is already in use`);
process.exit(1);
break;
default:
throw error;
}
});
return app;
}
Loading

0 comments on commit 76718f3

Please sign in to comment.