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
This diff is collapsed.
[![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