Commit edd4a923 authored by chinguyen's avatar chinguyen

Initial commit

parents
Pipeline #5587 failed with stages
# EditorConfig is awesome: http://EditorConfig.org
# top-most EditorConfig file
root = true
# Unix-style newlines with a newline ending every file
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
\ No newline at end of file
# These are supported funding model platforms
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: maximegris # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: maximegris # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
.idea
build
coverage
docs
node_modules
package-lock.json
yarn-lock.json
.github
.vscode
const path = require('path')
module.exports = {
"config": path.resolve('./src/sqlz/config', 'config.json'),
"models-path": path.resolve('./src/sqlz/models'),
"seeders-path": path.resolve('./src/sqlz/seeders'),
"migrations-path": path.resolve('./src/sqlz/migrations')
}
\ No newline at end of file
language: node_js
node_js:
- "node"
- "10"
install:
- npm install
script:
- npm run build
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug Typescript",
"type": "node",
"request": "launch",
"program": "${workspaceRoot}/src/server.ts",
"stopOnEntry": false,
"args": [],
"cwd": "${workspaceRoot}",
"preLaunchTask": "build",
"runtimeExecutable": null,
"runtimeArgs": [
"--nolazy"
],
"env": {
"NODE_ENV": "development"
},
"console": "internalConsole",
"sourceMaps": true,
"outDir": "${workspaceRoot}/build",
"restart": true
}
]
}
\ No newline at end of file
Apache License
==============
_Version 2.0, January 2004_
_&lt;<http://www.apache.org/licenses/>&gt;_
### Terms and Conditions for use, reproduction, and distribution
#### 1. Definitions
“License” shall mean the terms and conditions for use, reproduction, and
distribution as defined by Sections 1 through 9 of this document.
“Licensor” shall mean the copyright owner or entity authorized by the copyright
owner that is granting the License.
“Legal Entity” shall mean the union of the acting entity and all other entities
that control, are controlled by, or are under common control with that entity.
For the purposes of this definition, “control” means **(i)** the power, direct or
indirect, to cause the direction or management of such entity, whether by
contract or otherwise, or **(ii)** ownership of fifty percent (50%) or more of the
outstanding shares, or **(iii)** beneficial ownership of such entity.
“You” (or “Your”) shall mean an individual or Legal Entity exercising
permissions granted by this License.
“Source” form shall mean the preferred form for making modifications, including
but not limited to software source code, documentation source, and configuration
files.
“Object” form shall mean any form resulting from mechanical transformation or
translation of a Source form, including but not limited to compiled object code,
generated documentation, and conversions to other media types.
“Work” shall mean the work of authorship, whether in Source or Object form, made
available under the License, as indicated by a copyright notice that is included
in or attached to the work (an example is provided in the Appendix below).
“Derivative Works” shall mean any work, whether in Source or Object form, that
is based on (or derived from) the Work and for which the editorial revisions,
annotations, elaborations, or other modifications represent, as a whole, an
original work of authorship. For the purposes of this License, Derivative Works
shall not include works that remain separable from, or merely link (or bind by
name) to the interfaces of, the Work and Derivative Works thereof.
“Contribution” shall mean any work of authorship, including the original version
of the Work and any modifications or additions to that Work or Derivative Works
thereof, that is intentionally submitted to Licensor for inclusion in the Work
by the copyright owner or by an individual or Legal Entity authorized to submit
on behalf of the copyright owner. For the purposes of this definition,
“submitted” means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems, and
issue tracking systems that are managed by, or on behalf of, the Licensor for
the purpose of discussing and improving the Work, but excluding communication
that is conspicuously marked or otherwise designated in writing by the copyright
owner as “Not a Contribution.”
“Contributor” shall mean Licensor and any individual or Legal Entity on behalf
of whom a Contribution has been received by Licensor and subsequently
incorporated within the Work.
#### 2. Grant of Copyright License
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the Work and such
Derivative Works in Source or Object form.
#### 3. Grant of Patent License
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable (except as stated in this section) patent license to make, have
made, use, offer to sell, sell, import, and otherwise transfer the Work, where
such license applies only to those patent claims licensable by such Contributor
that are necessarily infringed by their Contribution(s) alone or by combination
of their Contribution(s) with the Work to which such Contribution(s) was
submitted. If You institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
Contribution incorporated within the Work constitutes direct or contributory
patent infringement, then any patent licenses granted to You under this License
for that Work shall terminate as of the date such litigation is filed.
#### 4. Redistribution
You may reproduce and distribute copies of the Work or Derivative Works thereof
in any medium, with or without modifications, and in Source or Object form,
provided that You meet the following conditions:
* **(a)** You must give any other recipients of the Work or Derivative Works a copy of
this License; and
* **(b)** You must cause any modified files to carry prominent notices stating that You
changed the files; and
* **(c)** You must retain, in the Source form of any Derivative Works that You distribute,
all copyright, patent, trademark, and attribution notices from the Source form
of the Work, excluding those notices that do not pertain to any part of the
Derivative Works; and
* **(d)** If the Work includes a “NOTICE” text file as part of its distribution, then any
Derivative Works that You distribute must include a readable copy of the
attribution notices contained within such NOTICE file, excluding those notices
that do not pertain to any part of the Derivative Works, in at least one of the
following places: within a NOTICE text file distributed as part of the
Derivative Works; within the Source form or documentation, if provided along
with the Derivative Works; or, within a display generated by the Derivative
Works, if and wherever such third-party notices normally appear. The contents of
the NOTICE file are for informational purposes only and do not modify the
License. You may add Your own attribution notices within Derivative Works that
You distribute, alongside or as an addendum to the NOTICE text from the Work,
provided that such additional attribution notices cannot be construed as
modifying the License.
You may add Your own copyright statement to Your modifications and may provide
additional or different license terms and conditions for use, reproduction, or
distribution of Your modifications, or for any such Derivative Works as a whole,
provided Your use, reproduction, and distribution of the Work otherwise complies
with the conditions stated in this License.
#### 5. Submission of Contributions
Unless You explicitly state otherwise, any Contribution intentionally submitted
for inclusion in the Work by You to the Licensor shall be under the terms and
conditions of this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify the terms of
any separate license agreement you may have executed with Licensor regarding
such Contributions.
#### 6. Trademarks
This License does not grant permission to use the trade names, trademarks,
service marks, or product names of the Licensor, except as required for
reasonable and customary use in describing the origin of the Work and
reproducing the content of the NOTICE file.
#### 7. Disclaimer of Warranty
Unless required by applicable law or agreed to in writing, Licensor provides the
Work (and each Contributor provides its Contributions) on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
including, without limitation, any warranties or conditions of TITLE,
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
solely responsible for determining the appropriateness of using or
redistributing the Work and assume any risks associated with Your exercise of
permissions under this License.
#### 8. Limitation of Liability
In no event and under no legal theory, whether in tort (including negligence),
contract, or otherwise, unless required by applicable law (such as deliberate
and grossly negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special, incidental,
or consequential damages of any character arising as a result of this License or
out of the use or inability to use the Work (including but not limited to
damages for loss of goodwill, work stoppage, computer failure or malfunction, or
any and all other commercial damages or losses), even if such Contributor has
been advised of the possibility of such damages.
#### 9. Accepting Warranty or Additional Liability
While redistributing the Work or Derivative Works thereof, You may choose to
offer, and charge a fee for, acceptance of support, warranty, indemnity, or
other liability obligations and/or rights consistent with this License. However,
in accepting such obligations, You may act only on Your own behalf and on Your
sole responsibility, not on behalf of any other Contributor, and only if You
agree to indemnify, defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason of your
accepting any such warranty or additional liability.
_END OF TERMS AND CONDITIONS_
### APPENDIX: How to apply the Apache License to your work
To apply the Apache License to your work, attach the following boilerplate
notice, with the fields enclosed by brackets `[]` replaced with your own
identifying information. (Don't include the brackets!) The text should be
enclosed in the appropriate comment syntax for the file format. We also
recommend that a file or class name and description of purpose be included on
the same “printed page” as the copyright notice for easier identification within
third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
\ No newline at end of file
[![Logo](./sequelize.png)](http://docs.sequelizejs.com)
[![Build Status](https://travis-ci.org/maximegris/typescript-express-sequelize.svg?branch=master)](https://travis-ci.org/maximegris/typescript-express-sequelize)
[![License](https://img.shields.io/badge/license-Apache2-blue.svg?style=flat)](https://github.com/maximegris/typescript-express-sequelize/blob/master/LICENSE.md)
# Introduction
Easily bootstrap your Typescript project with NodeJS + Express + Sequelize ORM. :heart:
## Installation
Run one of the command below
```bash
npm install
```
```bash
npm install -g yarn
yarn
```
The build tasks use **Gulp tasks runner**. Typescript is transpiled to Javascript in the /build directory.
This sample use PostgreSQL database but you can easily change it and use your favorite relational database (npm or yarn command) :
```bash
npm install --save mysql // For both mysql and mariadb dialects
npm install --save sqlite3
npm install --save tedious // MSSQL
```
## Configure your database
Sequelize configuration and entities can be found in /Src/sqlz directory.
| Directory | Description |
|---|---|
| config | Your database configuration. |
| migrations | Your database migrations scripts. Keep this files in Javascript and run sequelize db:migrate to migrate your database schema. |
| models | Sequelize entities. |
First, define your database schema in config/config.json file.
Use [Sequelize CLI](http://docs.sequelizejs.com/en/v3/docs/migrations/) to initialize your database.
In models/ directory, the index.ts file define the DbConnection interface. When you create a new Sequelize entity, add its reference in this interface to fully use Typescript's superpower !
## Run the project
```bash
npm start
```
Your web server is now exposed on http://localhost:3000
### GET /api/languages
curl -X GET -H 'Content-Type: application/json' http://localhost:3000/api/languages
### POST /api/languages
curl -X POST -H 'Content-Type: application/json' -d '{"label":"French","name":"fr"}' http://localhost:3000/api/languages
### GET /api/appusers
curl -X GET -H 'Content-Type: application/json' http://localhost:3000/api/appusers
### POST /api/appusers
curl -X POST -H 'Content-Type: application/json' -d '{"email":"foo@bar.com","pwd":"something"}' http://localhost:3000/api/appusers
## Build
```bash
npm run build
```
## Lint your code before you commit!
In a collaborative project, it's always a pain when you have to work on files not correctly formatted.
Now before each commit, yout typescript files are linted based on your tsconfig.json > .editorconfig > tslint.json files.
```bash
λ git commit -m "Example precommit"
> husky - npm run -s precommit
25l[14:22:30] Running tasks for src/**/*.ts [started]
[14:22:30] prettify [started]
[14:22:31] prettify [completed]
[14:22:31] git add [started]
[14:22:31] git add [completed]
[14:22:31] Running tasks for src/**/*.ts [completed]
25h25h[master 23c4321] Example precommit
1 file changed, 1 insertion(+), 1 deletion(-)
```
By the way you can also run the command with a npm script
```bash
npm run prettify
```
## Debug with Typescript and VSCode
Add breakpoints to your Typescript source code and launch in VSCode the "Debug Typescript" task.
When you'll access to an endpoint, you will be able to debug directly in your Typescript's files.
## Questions and issues
The [github issue tracker](https://github.com/maximegris/typescript-express-sequelize/issues) is **_only_** for bug reports and feature requests.
## Roadmap
- [x] Add Sequelize Typescript example with association
- [x] Manage multiple database configuration with NODE_ENV
- [ ] Add Swagger API Framework
theme: jekyll-theme-architect
\ No newline at end of file
"use strict";
let gulp = require("gulp");
let sourcemaps = require("gulp-sourcemaps");
let typescript = require("gulp-typescript");
let nodemon = require("gulp-nodemon");
let tslint = require("gulp-tslint");
let rimraf = require("rimraf");
let typedoc = require("gulp-typedoc");
let mocha = require("gulp-mocha");
let istanbul = require("gulp-istanbul");
let plumber = require("gulp-plumber");
let remapIstanbul = require("remap-istanbul/lib/gulpRemapIstanbul");
const CLEAN_BUILD = "clean:build";
const CLEAN_COVERAGE = "clean:coverage";
const CLEAN_DOC = "clean:doc";
const TSLINT = "tslint";
const COMPILE_TYPESCRIPT = "compile:typescript";
const COPY_STATIC_FILES = "copy:static";
const BUILD = "build";
const GENERATE_DOC = "generate:doc";
const PRETEST = "pretest";
const RUN_TESTS = "run:tests";
const TEST = "test";
const REMAP_COVERAGE = "remap:coverage";
const TS_SRC_GLOB = "./src/**/*.ts";
const TS_TEST_GLOB = "./test/**/*.ts";
const JS_TEST_GLOB = "./build/**/*.js";
const JS_SRC_GLOB = "./build/**/*.js";
const TS_GLOB = [TS_SRC_GLOB];
const STATIC_FILES = ['./src/**/*.json']
const tsProject = typescript.createProject("tsconfig.json");
// Removes the ./build directory with all its content.
gulp.task(CLEAN_BUILD, function (callback) {
rimraf("./build", callback);
});
// Removes the ./coverage directory with all its content.
gulp.task(CLEAN_COVERAGE, function (callback) {
rimraf("./coverage", callback);
});
// Removes the ./docs directory with all its content.
gulp.task(CLEAN_DOC, function (callback) {
rimraf("./docs", callback);
});
// Checks all *.ts-files if they are conform to the rules specified in tslint.json.
gulp.task(TSLINT, function () {
return gulp.src(TS_GLOB)
.pipe(tslint({ formatter: "verbose" }))
.pipe(tslint.report({
// set this to true, if you want the build process to fail on tslint errors.
emitError: false
}));
});
// Compiles all *.ts-files to *.js-files.
gulp.task(COPY_STATIC_FILES, function () {
return gulp.src(STATIC_FILES)
.pipe(gulp.dest("build"));
});
gulp.task(COMPILE_TYPESCRIPT, function () {
return gulp.src(TS_GLOB)
.pipe(sourcemaps.init())
.pipe(tsProject())
.pipe(sourcemaps.write(".", { sourceRoot: "../src" }))
.pipe(gulp.dest("build"));
});
// Runs all required steps for the build in sequence.
gulp.task(BUILD, gulp.series(CLEAN_BUILD, TSLINT, COMPILE_TYPESCRIPT, COPY_STATIC_FILES));
// Generates a documentation based on the code comments in the *.ts files.
gulp.task(GENERATE_DOC, gulp.series(CLEAN_DOC, function () {
return gulp.src(TS_SRC_GLOB)
.pipe(typedoc({
out: "docs",
target: "es5",
name: "Express + Sequelize",
module: "commonjs",
readme: "readme.md",
includeDeclarations: true,
version: true
}))
}));
// Sets up the istanbul coverage
gulp.task(PRETEST, function () {
return gulp.src(JS_SRC_GLOB)
.pipe(sourcemaps.init({ loadMaps: true }))
.pipe(istanbul({ includeUntested: true }))
.pipe(istanbul.hookRequire())
});
// Run the tests via mocha and generate a istanbul json report.
gulp.task(RUN_TESTS, function (callback) {
let mochaError;
gulp.src(JS_TEST_GLOB)
.pipe(plumber())
.pipe(mocha({ reporter: "spec" }))
.on("error", function (err) {
mochaError = err;
})
.pipe(istanbul.writeReports({
reporters: ["json"]
}))
.on("end", function () {
callback(mochaError);
});
});
// Remap Coverage to *.ts-files and generate html, text and json summary
gulp.task(REMAP_COVERAGE, function () {
return gulp.src("./coverage/coverage-final.json")
.pipe(remapIstanbul({
// basePath: ".",
fail: true,
reports: {
"html": "./coverage",
"json": "./coverage",
"text-summary": null,
"lcovonly": "./coverage/lcov.info"
}
}))
.pipe(gulp.dest("coverage"))
.on("end", function () {
console.log("--> For a more detailed report, check the ./coverage directory <--")
});
});
// Runs all required steps for testing in sequence.
gulp.task(TEST, gulp.series(BUILD, CLEAN_COVERAGE, PRETEST, RUN_TESTS, REMAP_COVERAGE));
// Runs the build task and starts the server every time changes are detected.
gulp.task("watch", gulp.series(BUILD, function () {
return nodemon({
ext: "ts json",
script: "build/server.js",
watch: ["src/*", "test/*"],
legacyWatch: true,
tasks: [BUILD]
});
}));
{
"name": "typescript-express-sequelize",
"version": "2.1.0",
"description": "Sample project with Express + Sequelize + Typescript",
"homepage": "https://github.com/maximegris/typescript-express-sequelize",
"author": {
"name": "Maxime GRIS",
"email": "maxime.gris@gmail.com"
},
"main": "build/src/server.js",
"keywords": [
"Node",
"Express",
"Typescript",
"Sequelize"
],
"scripts": {
"build": "gulp build",
"doc": "gulp generate:doc",
"start": "cross-env NODE_ENV=development gulp watch",
"start:prod": "cross-env NODE_ENV=production gulp watch",
"run:test": "cross-env NODE_ENV=test gulp test",
"tslint": "gulp tslint",
"prettify": "./node_modules/.bin/tsfmt -r --baseDir ./src",
"sqlz:migrate": "./node_modules/.bin/sequelize db:migrate",
"sqlz:undo": "./node_modules/.bin/sequelize db:migrate:undo",
"sqlz:new": "./node_modules/.bin/sequelize migration:create"
},
"lint-staged": {
"src/**/*.ts": [
"npm run prettify"
]
},
"dependencies": {
"body-parser": "1.19.0",
"cors": "2.8.5",
"cross-env": "7.0.0",
"express": "4.17.1",
"express-boom": "3.0.0",
"morgan": "1.9.1",
"pg": "^8.5.1",
"pg-hstore": "^2.3.3",
"sequelize": "^6.5.0",
"uuid": "3.4.0",
"winston": "3.2.1"
},
"devDependencies": {
"chai": "4.2.0",
"extendify": "1.0.0",
"glob": "7.1.6",
"gulp": "4.0.2",
"gulp-istanbul": "1.1.3",
"gulp-json-refs": "0.1.1",
"gulp-mocha": "7.0.2",
"gulp-nodemon": "2.4.2",
"gulp-plumber": "1.2.1",
"gulp-sourcemaps": "2.6.5",
"gulp-tslint": "8.1.4",
"gulp-typedoc": "2.2.4",
"gulp-typescript": "5.0.1",
"husky": "4.2.3",
"lint-staged": "10.0.7",
"remap-istanbul": "0.13.0",
"rimraf": "3.0.2",
"sequelize-cli": "5.5.1",
"tslint": "6.0.0",
"typedoc": "0.16.10",
"typescript": "3.8.2",
"typescript-formatter": "7.2.2"
},
"engines": {
"node": ">=4.0.0"
},
"license": "SEE LICENSE IN LICENSE.md",
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
}
}
{
"development": {
"username": "postgres",
"password": "chinguyen",
"database": "node_sequelize",
"host": "127.0.0.1",
"port": 5432,
"dialect": "postgres"
}
}
\ No newline at end of file
import * as LanguagesDao from './languages'
import * as AppUserDao from './appusers'
export { LanguagesDao }
export { AppUserDao }
import * as uuid from 'uuid'
import { AppUser } from './../sqlz/models/appuser'
import { Language } from '../sqlz/models/language'
export function create(appUser: any): Promise<any> {
return Language.findOne({
where: { name: 'fr' }
})
.then(language => {
return AppUser
.create({
id: uuid.v1(),
email: appUser.email,
pwd: appUser.pwd,
languageId: language.get('id')
})
})
}
export function findAll(): Promise<any> {
return AppUser
.findAll({ include: [{ all: true }] })
}
export function login(appUser: any): Promise<any> {
return AppUser
.findOne({
where: {
email: appUser.email,
pwd: appUser.pwd
},
include: [Language]
})
}
import * as uuid from 'uuid'
import { Language } from './../sqlz/models/language'
export function create(language: any): Promise<any> {
return Language
.create({
id: uuid.v1(),
label: language.label,
name: language.name
})
}
export function findAll(): Promise<any> {
return Language
.findAll()
}
import * as LanguageController from './languages/_index'
import * as AppUserController from './appusers/_index'
export { LanguageController, AppUserController }
import * as AppUserGet from './appusers.get'
import * as AppUserPost from './appusers.post'
export { AppUserGet, AppUserPost }
import { Request, Response } from 'express'
import { AppUserDao } from '../../dao/_index'
export function list(req: Request, res: Response) {
return AppUserDao
.findAll()
.then(appusers => res.status(200).send(appusers))
.catch(error => res.boom.badRequest(error))
}
import { Request, Response } from 'express'
import { AppUserDao } from '../../dao/_index'
export function create(req: Request, res: Response) {
req.checkBody('pwd', 'Password is required').notEmpty()
req.checkBody('email', 'Email is required').notEmpty()
req.checkBody('email', 'A valid email is required').isEmail()
req.getValidationResult()
.then(function(result) {
if (result.isEmpty()) {
return AppUserDao.create(req.body)
.then(appuser => res.status(201).send(appuser))
.catch(error => res.boom.badRequest(error))
} else {
res.boom.badRequest('Validation errors', result.mapped())
}
})
}
export function login(req: Request, res: Response) {
req.checkBody('pwd', 'Password is required').notEmpty()
req.checkBody('email', 'Email is required').notEmpty()
req.checkBody('email', 'A valid email is required').isEmail()
req.getValidationResult()
.then(function(result) {
if (result.isEmpty()) {
return AppUserDao.login(req.body)
} else {
res.boom.badRequest('Validation errors', result.mapped())
}
})
.then(appuser => res.status(200).send(appuser))
.catch(error => res.boom.badRequest(error))
}
import * as LanguageGet from './languages.get'
import * as LanguagePost from './languages.post'
export { LanguageGet, LanguagePost }
import { Request, Response } from 'express'
import { LanguagesDao } from '../../dao/_index'
export function list(req: Request, res: Response) {
return LanguagesDao
.findAll()
.then(languages => res.status(200).send(languages))
.catch(error => res.boom.badRequest(error))
}
import { Request, Response } from 'express'
import { LanguagesDao } from '../../dao/_index'
export function create(req: Request, res: Response) {
return LanguagesDao.create(req.body)
.then(language => res.status(201).send(language))
.catch(error => res.boom.badRequest(error))
}
declare namespace Express {
export interface Response {
boom: any
}
}
import * as winston from 'winston'
import { Express, Request, Response } from 'express'
import * as LanguagesRoutes from './languages'
import * as AppUserRoutes from './appusers'
export function initRoutes(app: Express) {
winston.log('info', '--> Initialisations des routes')
app.get('/api', (req: Request, res: Response) => res.status(200).send({
message: 'server is running!'
}))
LanguagesRoutes.routes(app)
AppUserRoutes.routes(app)
app.all('*', (req: Request, res: Response) => res.boom.notFound())
}
import { Express } from 'express'
import { AppUserController } from '../endpoints/_index'
export function routes(app: Express) {
app.get('/api/appUsers', AppUserController.AppUserGet.list)
app.post('/api/appUsers', AppUserController.AppUserPost.create)
app.post('/api/appUsers/login', AppUserController.AppUserPost.login)
}
import { Express } from 'express'
import { LanguageController } from '../endpoints/_index'
export function routes(app: Express) {
app.get('/api/languages', LanguageController.LanguageGet.list)
app.post('/api/languages', LanguageController.LanguagePost.create)
}
import * as express from 'express'
import * as winston from 'winston'
import * as boom from 'express-boom'
import * as morgan from 'morgan'
import * as cors from 'cors'
import { json, urlencoded } from 'body-parser'
import { Express } from 'express'
import * as routes from './routes/_index'
const PORT: number = 3000
/**
* Root class of your node server.
* Can be used for basic configurations, for instance starting up the server or registering middleware.
*/
export class Server {
private app: Express
constructor() {
this.app = express()
// Express middleware
this.app.use(cors({
optionsSuccessStatus: 200
}))
this.app.use(urlencoded({
extended: true
}))
this.app.use(json())
this.app.use(boom())
this.app.use(morgan('combined'))
this.app.listen(PORT, () => {
winston.log('info', '--> Server successfully started at port %d', PORT)
})
routes.initRoutes(this.app)
}
getApp() {
return this.app
}
}
new Server()
{
"development": {
"username": "postgres",
"password": "chinguyen",
"database": "node_sequelize",
"host": "127.0.0.1",
"port": 5432,
"dialect": "postgres"
}
}
\ No newline at end of file
module.exports = {
up: (queryInterface, Sequelize) =>
queryInterface.createTable('Languages', {
id: {
allowNull: false,
type: Sequelize.UUID,
defaultValue: Sequelize.UUIDV1,
primaryKey: true
},
label: {
allowNull: false,
type: Sequelize.STRING(255)
},
name: {
allowNull: false,
type: Sequelize.STRING(50),
unique: true
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
})
,
down: (queryInterface, Sequelize) => queryInterface.dropTable('Languages')
}
module.exports = {
up: (queryInterface, Sequelize) =>
queryInterface.createTable('AppUsers', {
id: {
allowNull: false,
type: Sequelize.UUID,
defaultValue: Sequelize.UUIDV1,
primaryKey: true
},
email: {
allowNull: false,
type: Sequelize.STRING(50),
unique: true
},
pwd: {
allowNull: false,
type: Sequelize.STRING(255)
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
},
languageId: {
type: Sequelize.UUID,
allowNull: false,
onDelete: 'CASCADE',
references: {
model: 'Languages',
key: 'id',
as: 'languageId',
}
}
})
,
down: (queryInterface, Sequelize) => queryInterface.dropTable('AppUsers')
}
import { Sequelize } from 'sequelize'
const config = require('../config/config.json')
const dbConfig = config[process.env.NODE_ENV]
const sequelize = new Sequelize(
dbConfig['database'],
dbConfig['username'],
dbConfig['password'],
dbConfig
)
export default sequelize
import { Model, STRING, UUID, Deferrable } from 'sequelize'
import sequelize from './_index'
import { Language } from './language'
export class AppUser extends Model {
}
export class AppUserModel {
id: string
name: string
pwd: string
createdAt: Date
updatedAt: Date
}
AppUser.init(
{
email: STRING(50),
pwd: STRING(50)
},
{ sequelize, modelName: 'AppUser' }
)
AppUser.belongsTo(Language, {
foreignKey: 'languageId'
})
import { Model, STRING, UUID } from 'sequelize'
import sequelize from './_index'
import { AppUser } from './appuser'
export class Language extends Model {
}
export class LanguageModel {
id: string
label: string
name: string
createdAt: Date
updatedAt: Date
}
Language.init(
{
label: STRING(255),
name: STRING(50)
},
{ sequelize, modelName: 'Language' }
)
// This is only for test demonstration purposes, remove this as soon as you implemented your own tests.
export function addTwo(input: number): number {
input += 2
return input
}
import { expect } from 'chai'
import { addTwo } from '../src/test'
describe('Testing demo function', () => {
it('Should add two to input', () => {
let input: number = 5
let result = addTwo(input)
expect(result).to.eq(input + 2)
})
})
{
"compileOnSave": false,
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"declaration": false,
"noImplicitAny": false,
"removeComments": true,
"noLib": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"sourceMap": true,
"typeRoots": [
"node_modules/@types"
],
"lib": [
"es2017",
"es2016",
"es2015",
"dom"
]
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules"
]
}
{
"rules": {
"class-name": true,
"comment-format": [
true,
"check-space"
],
"indent": [
true,
"spaces"
],
"no-duplicate-variable": true,
"no-eval": true,
"no-internal-module": true,
"no-trailing-whitespace": true,
"no-unsafe-finally": true,
"no-var-keyword": true,
"one-line": [
true,
"check-open-brace",
"check-whitespace"
],
"quotemark": [
true,
"single"
],
"semicolon": [
true,
"never"
],
"triple-equals": [
true,
"allow-null-check"
],
"typedef-whitespace": [
true,
{
"call-signature": "nospace",
"index-signature": "nospace",
"parameter": "nospace",
"property-declaration": "nospace",
"variable-declaration": "nospace"
}
],
"variable-name": [
true,
"ban-keywords"
],
"whitespace": [
true,
"check-branch",
"check-decl",
"check-operator",
"check-separator",
"check-type"
]
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment