├── README.md ├── node-express-psql ├── test │ ├── testUtils │ │ ├── data │ │ │ ├── projects.json │ │ │ └── tasks.json │ │ └── models │ │ │ ├── Task.js │ │ │ └── Project.js │ └── services │ │ ├── taskServiceTest.js │ │ └── projectServiceTest.js ├── .eslintrc.js ├── src │ ├── config │ │ ├── sequelize.js │ │ ├── express.js │ │ ├── config.js │ │ └── logging.js │ ├── routes │ │ ├── routes.js │ │ ├── projectRoutes.js │ │ └── taskRoutes.js │ ├── factories │ │ ├── taskFactory.js │ │ ├── projectFactory.js │ │ └── index.js │ ├── server.js │ ├── middleware │ │ └── errorHandlers.js │ ├── models │ │ ├── Task.js │ │ └── Project.js │ └── services │ │ ├── projectService.js │ │ └── taskService.js ├── build │ ├── start-local-tests.sh │ └── start-local-server.sh ├── package.json └── README.md ├── .gitignore └── LICENSE /README.md: -------------------------------------------------------------------------------- 1 | # Boilerplate NodeJS projects 2 | -------------------------------------------------------------------------------- /node-express-psql/test/testUtils/data/projects.json: -------------------------------------------------------------------------------- 1 | TODO 2 | -------------------------------------------------------------------------------- /node-express-psql/test/testUtils/data/tasks.json: -------------------------------------------------------------------------------- 1 | // TODO 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | */node_modules 2 | .DS_Store 3 | combined.log 4 | error.log 5 | -------------------------------------------------------------------------------- /node-express-psql/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | "extends": "google", 3 | "parser": "babel-eslint" 4 | }; 5 | -------------------------------------------------------------------------------- /node-express-psql/src/config/sequelize.js: -------------------------------------------------------------------------------- 1 | const {sequelize} = require('../factories'); 2 | module.exports = sequelize; 3 | -------------------------------------------------------------------------------- /node-express-psql/src/routes/routes.js: -------------------------------------------------------------------------------- 1 | var router = require('express').Router(); 2 | 3 | router.use('/', require('./projectRoutes')); 4 | router.use('/', require('./taskRoutes')); 5 | 6 | module.exports = router; 7 | -------------------------------------------------------------------------------- /node-express-psql/build/start-local-tests.sh: -------------------------------------------------------------------------------- 1 | DB_USER= \ 2 | DB_HOST= \ 3 | DB_PASSWORD= \ 4 | DB_DATABASE= \ 5 | DB_PORT= \ 6 | DB_DIALECT=postgres \ 7 | DB_POOL_MAX=5 \ 8 | DB_POOL_MIN=0 \ 9 | DB_POOL_ACQUIRE=30000 \ 10 | DB_POOL_IDLE=10000 \ 11 | PORT=8081 \ 12 | LOGGING_LEVEL=debug \ 13 | NODE_ENV=test \ 14 | mocha --recursive 15 | -------------------------------------------------------------------------------- /node-express-psql/build/start-local-server.sh: -------------------------------------------------------------------------------- 1 | DB_USER= \ 2 | DB_HOST=localhost \ 3 | DB_PASSWORD= \ 4 | DB_DATABASE= \ 5 | DB_PORT= \ 6 | DB_DIALECT=postgres \ 7 | DB_POOL_MAX=5 \ 8 | DB_POOL_MIN=0 \ 9 | DB_POOL_ACQUIRE=30000 \ 10 | DB_POOL_IDLE=10000 \ 11 | PORT=8081 \ 12 | LOGGING_LEVEL=debug \ 13 | NODE_ENV=local \ 14 | babel-watch ./src/server.js 15 | -------------------------------------------------------------------------------- /node-express-psql/src/factories/taskFactory.js: -------------------------------------------------------------------------------- 1 | const config = require('../config/config'); 2 | 3 | function createTask(nodeEnv=config.env){ 4 | let taskModel; 5 | // if the node env is test use the mock Task 6 | if(nodeEnv === 'test'){ 7 | taskModel = require('../../test/testUtils/models/Task'); 8 | } 9 | else{ 10 | taskModel = require('../models/Task'); 11 | } 12 | return taskModel 13 | } 14 | 15 | module.exports = createTask(); 16 | -------------------------------------------------------------------------------- /node-express-psql/src/factories/projectFactory.js: -------------------------------------------------------------------------------- 1 | const config = require('../config/config'); 2 | 3 | function createProject(nodeEnv=config.env){ 4 | let projectModel; 5 | // if the node env is test use the mock Projects 6 | if(nodeEnv === 'test'){ 7 | projectModel = require('../../test/testUtils/models/Project'); 8 | } 9 | else{ 10 | projectModel = require('../models/Project'); 11 | } 12 | return projectModel 13 | } 14 | 15 | module.exports = createProject(); 16 | -------------------------------------------------------------------------------- /node-express-psql/src/server.js: -------------------------------------------------------------------------------- 1 | require('babel-core/register'); 2 | require('babel-polyfill'); 3 | 4 | const config = require('./config/config'); 5 | const app = require('./config/express'); 6 | const sequelize = require('./config/sequelize'); 7 | const logger = require('./config/logging'); 8 | 9 | 10 | logger.info("Starting the app...") 11 | sequelize.sync({force: true}) 12 | .then(() => { 13 | app.listen( 14 | config.port, 15 | () => console.log(`Example NodeJS, PSQL, and Express API running on port ${config.port}`) 16 | ); 17 | } 18 | ); 19 | -------------------------------------------------------------------------------- /node-express-psql/src/middleware/errorHandlers.js: -------------------------------------------------------------------------------- 1 | 2 | function logErrors (err, req, res, next) { 3 | console.error(err.stack) 4 | next(err) 5 | }; 6 | 7 | function clientErrorHandler (err, req, res, next) { 8 | if (req.xhr) { 9 | res.status(500).send({ error: 'Something failed!' }) 10 | } else { 11 | next(err) 12 | } 13 | }; 14 | 15 | function errorHandler (err, req, res, next) { 16 | res.status(500).send({ error: 'Base handler: ' + err }) 17 | } 18 | 19 | 20 | exports.logErrors = logErrors; 21 | exports.clientErrorHandler = clientErrorHandler; 22 | exports.errorHandler = logErrors; 23 | -------------------------------------------------------------------------------- /node-express-psql/src/config/express.js: -------------------------------------------------------------------------------- 1 | const cors = require('cors'); 2 | const bodyParser = require('body-parser'); 3 | const express = require('express'); 4 | 5 | var handlers = require('../middleware/errorHandlers') 6 | var routes = require('../routes/routes') 7 | 8 | const app = express(); 9 | 10 | app.use(cors()); 11 | app.use(bodyParser.json()); 12 | 13 | // Add routes to the express app 14 | app.use(routes); 15 | 16 | // Define error handlers 17 | app.use(handlers.logErrors); 18 | app.use(handlers.clientErrorHandler); 19 | app.use(handlers.logErrors); 20 | 21 | // Export the fully configured express app. 22 | module.exports = app; 23 | -------------------------------------------------------------------------------- /node-express-psql/test/testUtils/models/Task.js: -------------------------------------------------------------------------------- 1 | var SequelizeMock = require('sequelize-mock'); 2 | 3 | var dbMock = new SequelizeMock(); 4 | 5 | // TODO Pull mock task from testUtils data 6 | module.exports = (sequelize, DataTypes) => { 7 | let taskMock = dbMock.define('Task'); 8 | taskMock.$queueResult([ 9 | taskMock.build({ 10 | id: 1, 11 | name: 'Task 1', 12 | description: 'Task 1 Desc', 13 | status: 'ToDo' 14 | }), 15 | taskMock.build({ 16 | id: 2, 17 | name: 'Task 2', 18 | description: 'Task 2 Desc', 19 | status: 'ToDo' 20 | }) 21 | ]); 22 | return taskMock; 23 | } 24 | -------------------------------------------------------------------------------- /node-express-psql/test/testUtils/models/Project.js: -------------------------------------------------------------------------------- 1 | var SequelizeMock = require('sequelize-mock'); 2 | 3 | var dbMock = new SequelizeMock(); 4 | 5 | // TODO Pull mock projects from testUtils data 6 | module.exports = (sequelize, DataTypes) => { 7 | let projectMock = dbMock.define('Project'); 8 | projectMock.$queueResult([ 9 | projectMock.build({ 10 | id: 1, 11 | name: 'Project 1', 12 | description: 'Project 1 Desc', 13 | status: 'ToDo' 14 | }), 15 | projectMock.build({ 16 | id: 2, 17 | name: 'Project 2', 18 | description: 'Project 2 Desc', 19 | status: 'ToDo' 20 | }) 21 | ]); 22 | 23 | return projectMock; 24 | } 25 | -------------------------------------------------------------------------------- /node-express-psql/src/config/config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | env: process.env.NODE_ENV, 3 | port: process.env.PORT || 8081, 4 | db: { 5 | database: process.env.DB_DATABASE, 6 | user: process.env.DB_USER, 7 | password: process.env.DB_PASSWORD, 8 | options: { 9 | host: process.env.HOST, 10 | dialect: process.env.DB_DIALECT, 11 | pool: { 12 | poolMax: process.env.DB_POOL_MAX, 13 | poolMin: process.env.DB_POOL_MIN, 14 | poolAcquire: process.env.DB_POOL_ACQUIRE, 15 | poolIdle: process.env.DB_POOL_IDLE, 16 | port: process.env.DB_PORT, 17 | }, 18 | }, 19 | }, 20 | logger: { 21 | logging_level: process.env.LOGGING_LEVEL || 'error', 22 | }, 23 | }; 24 | -------------------------------------------------------------------------------- /node-express-psql/src/models/Task.js: -------------------------------------------------------------------------------- 1 | 2 | module.exports = (sequelize, DataTypes) => { 3 | var Task = sequelize.define('Task', { 4 | id: { 5 | type: DataTypes.BIGINT, 6 | primaryKey: true, 7 | autoIncrement: true, 8 | allowNull: false, 9 | }, 10 | name: { 11 | type: DataTypes.STRING, 12 | allowNull: false, 13 | }, 14 | description: { 15 | type: DataTypes.STRING, 16 | allowNull: false, 17 | }, 18 | status: { 19 | type: DataTypes.ENUM('ToDo', 'InProgress', 'Done', 'Deleted'), 20 | defaultValue: 'ToDo', 21 | allowNull: false, 22 | }, 23 | }, 24 | { 25 | tableName: 'Tasks', 26 | underscored: true, 27 | }); 28 | 29 | return Task; 30 | }; 31 | -------------------------------------------------------------------------------- /node-express-psql/src/models/Project.js: -------------------------------------------------------------------------------- 1 | 2 | module.exports = (sequelize, DataTypes) => { 3 | var Project = sequelize.define('Project', { 4 | id: { 5 | type: DataTypes.BIGINT, 6 | primaryKey: true, 7 | autoIncrement: true, 8 | allowNull: false, 9 | }, 10 | name: { 11 | type: DataTypes.STRING, 12 | allowNull: false, 13 | }, 14 | description: { 15 | type: DataTypes.STRING, 16 | allowNull: false, 17 | }, 18 | status: { 19 | type: DataTypes.ENUM('ToDo', 'InProgress', 'Done', 'Deleted'), 20 | defaultValue: 'ToDo', 21 | allowNull: false, 22 | }, 23 | }, 24 | { 25 | tableName: 'Projects', 26 | underscored: true, 27 | }); 28 | 29 | return Project; 30 | } 31 | -------------------------------------------------------------------------------- /node-express-psql/src/config/logging.js: -------------------------------------------------------------------------------- 1 | const winston = require('winston'); 2 | 3 | const config = require('./config'); 4 | 5 | const logger = winston.createLogger({ 6 | level: config.logger.logging_level, 7 | format: winston.format.json(), 8 | defaultMeta: {service: 'user-service'}, 9 | transports: [ 10 | new winston.transports.File({filename: 'error.log', level: 'error'}), 11 | new winston.transports.File({filename: 'combined.log'}), 12 | ], 13 | }); 14 | 15 | // 16 | // If we're not in production then log to the `console` with the format: 17 | // `${info.level}: ${info.message} JSON.stringify({ ...rest }) ` 18 | // 19 | if (config.env !== 'production') { 20 | logger.add(new winston.transports.Console({ 21 | format: winston.format.simple(), 22 | })); 23 | } 24 | 25 | module.exports = logger; 26 | -------------------------------------------------------------------------------- /node-express-psql/test/services/taskServiceTest.js: -------------------------------------------------------------------------------- 1 | const taskService = require('../../src/services/taskService'); 2 | const chai = require('chai'); 3 | const expect = chai.expect; 4 | const assert = chai.assert; 5 | 6 | chai.use(require('chai-like')) 7 | chai.use(require('chai-things')) 8 | 9 | describe('Get active tasks', function () { 10 | it("Should return a list of active tasks", function (done) { 11 | taskService.getActiveTasks().then(function (tasks) { 12 | expect(tasks).to.include.something.deep.like({ 13 | id: 1, 14 | name: 'Task 1', 15 | description: 'Task 1 Desc', 16 | status: 'ToDo', 17 | }); 18 | expect(tasks).to.include.something.deep.like({ 19 | id: 2, 20 | name: 'Task 2', 21 | description: 'Task 2 Desc', 22 | status: 'ToDo', 23 | }); 24 | 25 | done(); 26 | }).catch(done); 27 | }); 28 | }); 29 | -------------------------------------------------------------------------------- /node-express-psql/test/services/projectServiceTest.js: -------------------------------------------------------------------------------- 1 | const projectService = require('../../src/services/projectService'); 2 | const chai = require('chai'); 3 | const expect = chai.expect; 4 | const assert = chai.assert; 5 | 6 | chai.use(require('chai-like')) 7 | chai.use(require('chai-things')) 8 | 9 | describe('Get active tasks', function () { 10 | it("Should return a list of active projects", function (done) { 11 | projectService.getActiveProjects().then(function (projects) { 12 | expect(projects).to.include.something.deep.like({ 13 | id: 1, 14 | name: 'Project 1', 15 | description: 'Project 1 Desc', 16 | status: 'ToDo', 17 | }); 18 | expect(projects).to.include.something.deep.like({ 19 | id: 2, 20 | name: 'Project 2', 21 | description: 'Project 2 Desc', 22 | status: 'ToDo', 23 | }); 24 | 25 | done(); 26 | }).catch(done); 27 | }); 28 | }); 29 | -------------------------------------------------------------------------------- /node-express-psql/src/factories/index.js: -------------------------------------------------------------------------------- 1 | /** This segment of code was pulled from the sequelize RTD 2 | * Source: https://sequelize.readthedocs.io/en/1.7.0/articles/express/ 3 | * 4 | * The code is responsible for collecting all the models into an object 5 | * that is exported. This simplifies the Sequelize setup and imports. 6 | */ 7 | 8 | 'use strict'; 9 | const fs = require('fs'); 10 | const path = require('path'); 11 | const Sequelize = require('sequelize'); 12 | const config = require('../config/config'); 13 | var db = {} 14 | 15 | const sequelize = new Sequelize( 16 | config.db.database, 17 | config.db.user, 18 | config.db.password, 19 | config.db.options, 20 | ); 21 | 22 | fs 23 | .readdirSync(__dirname) 24 | .filter((file) => 25 | file !== 'index.js' 26 | ) 27 | .forEach((file) => { 28 | const model = sequelize.import(path.join(__dirname, file)); 29 | db[model.name] = model; 30 | }); 31 | 32 | 33 | db.sequelize = sequelize; 34 | db.Sequelize = Sequelize; 35 | 36 | db.Project.hasMany(db.Task, {as: 'tasks'}); 37 | db.Task.belongsTo(db.Project, {as: 'project'}); 38 | 39 | module.exports = db; 40 | -------------------------------------------------------------------------------- /node-express-psql/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "node-express-psql", 3 | "version": "1.0.0", 4 | "description": "Example API using node, express, and psql", 5 | "main": "server.js", 6 | "scripts": { 7 | "test": "bash ./build/start-local-tests.sh || true", 8 | "local": "bash ./build/start-local-server.sh" 9 | }, 10 | "author": "Austyn Herman", 11 | "license": "ISC", 12 | "devDependencies": { 13 | "@babel/core": "^7.6.4", 14 | "@babel/preset-env": "^7.6.3", 15 | "@babel/register": "^7.6.2", 16 | "babel-cli": "^6.26.0", 17 | "babel-core": "^6.26.3", 18 | "babel-eslint": "^10.0.1", 19 | "babel-loader": "^8.0.5", 20 | "babel-polyfill": "^6.26.0", 21 | "babel-preset-env": "^1.7.0", 22 | "babel-preset-es2015": "^6.24.1", 23 | "babel-preset-stage-0": "^6.24.1", 24 | "babel-watch": "^2.0.7", 25 | "chai": "^4.2.0", 26 | "chai-like": "^1.1.1", 27 | "chai-things": "^0.2.0", 28 | "eslint": "^5.11.1", 29 | "eslint-config-google": "^0.11.0", 30 | "mocha": "^6.2.2", 31 | "sequelize-mock": "^0.10.2" 32 | }, 33 | "dependencies": { 34 | "cors": "^2.8.5", 35 | "dotenv": "^8.1.0", 36 | "express": "^4.17.1", 37 | "express-session": "^1.16.2", 38 | "jwks-rsa": "^1.6.0", 39 | "method-override": "^3.0.0", 40 | "pg": "^7.7.1", 41 | "pg-hstore": "^2.3.2", 42 | "sequelize": "^4.44.2", 43 | "winston": "^3.2.1" 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /node-express-psql/src/services/projectService.js: -------------------------------------------------------------------------------- 1 | const Sequelize = require('sequelize'); 2 | const {Project} = require('../factories'); 3 | const {Task} = require('../factories'); 4 | const Op = Sequelize.Op; 5 | 6 | /** 7 | * Fetches Projects from the Database that do not have the 'Deleted' status. 8 | * @return {Array.} A list of the active projects in the database. 9 | */ 10 | async function getActiveProjects() { 11 | try { 12 | let projectList = await Project.findAll({ 13 | where: { 14 | status: { 15 | [Op.ne]: 'Deleted', 16 | }, 17 | }, 18 | attributes: ['id', 'name', 'description'], 19 | include: [{ 20 | model: Task, 21 | as: 'tasks' 22 | }], 23 | }); 24 | return projectList; 25 | } 26 | catch(error){ 27 | throw error; 28 | } 29 | }; 30 | 31 | /** 32 | * Creates a Project in the database. 33 | * @param {string} name - The name of the project. 34 | * @param {string} description - The description of the project. 35 | * @return {json} The Project that was created. 36 | */ 37 | async function createProject(name, description) { 38 | try { 39 | let project = await Project.create( 40 | { 41 | name: name, 42 | description: description 43 | }, 44 | {} 45 | ); 46 | return project; 47 | } 48 | catch(error){ 49 | throw error; 50 | } 51 | }; 52 | 53 | exports.getActiveProjects = getActiveProjects; 54 | exports.createProject = createProject; 55 | -------------------------------------------------------------------------------- /node-express-psql/src/routes/projectRoutes.js: -------------------------------------------------------------------------------- 1 | const projectService = require('../services/projectService'); 2 | 3 | var router = require('express').Router(); 4 | 5 | 6 | router.get('/projects/active', 7 | /** 8 | * Express path retrieving active Projects in the database. 9 | * @param {Object} req - The express request object. 10 | * @param {Object} res - The express response object. 11 | * @param {callback} next - Callback for propagating any errors up to the express error handler. 12 | * @return {Array.} A list of active Tasks. 13 | */ 14 | async function (req, res, next) { 15 | try{ 16 | let projectList = await projectService.getActiveProjects() 17 | res.send(projectList) 18 | } 19 | catch(error){ 20 | next(error) 21 | } 22 | } 23 | ); 24 | 25 | router.post('/projects/create', 26 | /** 27 | * Express path for creating a new Project in the database. 28 | * @param {Object} req - The express request object. 29 | * @param {Object} res - The express response object. 30 | * @param {callback} next - Callback for propegating any errors up to the express error handler. 31 | * @return {json} The Project that was created. 32 | */ 33 | async function (req, res, next) { 34 | try{ 35 | let name = req.body.name; 36 | let description = req.body.description; 37 | let projectList = await projectService.createProject(name, description); 38 | res.send(projectList); 39 | } 40 | catch(error){ 41 | next(error) 42 | } 43 | } 44 | ); 45 | 46 | module.exports = router; 47 | -------------------------------------------------------------------------------- /node-express-psql/src/services/taskService.js: -------------------------------------------------------------------------------- 1 | const Sequelize = require('sequelize'); 2 | const Op = Sequelize.Op; 3 | 4 | const {Project} = require('../factories'); 5 | const {Task} = require('../factories'); 6 | 7 | /** 8 | * Creates a Task in the database. 9 | * @param {string} name - The name of the task. 10 | * @param {string} description - The description of the task. 11 | * @param {string} projectId - The project the task belongs to. 12 | * @return {json} The Task that was created. 13 | */ 14 | async function createTask(name, description, projectId=null) { 15 | try { 16 | let task = await Task.create( 17 | { 18 | name: name, 19 | description: description, 20 | }, 21 | {} 22 | ); 23 | if(projectId){ 24 | await task.setProject(projectId); 25 | } 26 | return task; 27 | } 28 | catch(error){ 29 | throw error; 30 | } 31 | }; 32 | 33 | /** 34 | * Fetches Tasks from the Database that do not have the 'Deleted' status. 35 | * @return {Array.} A list of the active tasks in the database. 36 | */ 37 | async function getActiveTasks() { 38 | try { 39 | let taskList = await Task.findAll({ 40 | where: { 41 | status: { 42 | [Op.ne]: 'Deleted', 43 | }, 44 | }, 45 | attributes: ['id', 'name', 'description'], 46 | include: [{ 47 | model: Project, 48 | as: 'project' 49 | }], 50 | }); 51 | return taskList; 52 | } 53 | catch(error){ 54 | throw error; 55 | } 56 | }; 57 | 58 | 59 | exports.createTask = createTask; 60 | exports.getActiveTasks = getActiveTasks; 61 | -------------------------------------------------------------------------------- /node-express-psql/src/routes/taskRoutes.js: -------------------------------------------------------------------------------- 1 | const taskService = require('../services/taskService'); 2 | 3 | var router = require('express').Router(); 4 | 5 | 6 | router.get('/tasks/active', 7 | /** 8 | * Express path retrieving active Tasks in the database. 9 | * @param {Object} req - The express request object. 10 | * @param {Object} res - The express response object. 11 | * @param {callback} next - Callback for propegating any errors up to the express error handler. 12 | * @return {Array.} A list of active Tasks. 13 | */ 14 | async function (req, res, next) { 15 | try{ 16 | let task = await taskService.getActiveTasks(); 17 | res.send(task); 18 | } 19 | catch(error){ 20 | next(error) 21 | } 22 | } 23 | ); 24 | 25 | router.post('/tasks/create', 26 | /** 27 | * Express path for creating a new Task in the database. 28 | * @param {Object} req - The express request object. 29 | * @param {Object} res - The express response object. 30 | * @param {callback} next - Callback for propegating any errors up to the express error handler. 31 | * @return {json} The Task that was created. 32 | */ 33 | async function (req, res, next) { 34 | try{ 35 | let taskList; 36 | let name = req.body.name; 37 | let description = req.body.description; 38 | if('projectId' in req.body){ 39 | let projectId = req.body.projectId; 40 | taskList = await taskService.createTask(name, description, projectId); 41 | } 42 | else{ 43 | taskList = await taskService.createTask(name, description); 44 | } 45 | 46 | res.send(taskList) 47 | } 48 | catch(error){ 49 | next(error) 50 | } 51 | } 52 | ); 53 | 54 | module.exports = router; 55 | -------------------------------------------------------------------------------- /node-express-psql/README.md: -------------------------------------------------------------------------------- 1 | # Node Express PSQL API Quickstart 2 | This module contains boilerplate code for creating a NodeJS, Express, and PSQL API. 3 | 4 | # Dependencies 5 | ### OS X 6 | ##### Installing Node 7 | [Install NodeJS][install-node] from the official site. 8 | OR 9 | Using homebrew 10 | ``` 11 | $brew install node 12 | ``` 13 | 14 | ##### Local Postgress Database 15 | The [Postgress Mac App][postgress-mac] provides all the necessary features for running a local Postgres database. Follow the configuration and setup guide at the link. 16 | 17 | NOTE: 18 | After setting up the postgres local database the following file will need to be updated with the database details. 19 | `./node-express-psql/build/start-local-server.sh` 20 | Update the following fields: 21 | - DB_USER 22 | - DB_PASSWORD (Locally this may be empty) 23 | - DB_DATABASE 24 | - DB_PORT 25 | 26 | ##### Node Dependencies 27 | Running the following will install all the Node dependencies for running the API. 28 | ``` 29 | $cd node-express-psql 30 | $npm install 31 | ``` 32 | 33 | ### Other Operating Systems 34 | *Coming soon* 35 | 36 | # Running the API 37 | The API is set up to run locally using the following command 38 | ``` 39 | $cd node-express-psql 40 | $npm run local 41 | ``` 42 | Running local targets the `./node-express-psql/build/start-local-server.sh` 43 | build script. Different run configurations can be added to the `./node-express-psql/package.json` under scripts. 44 | 45 | # Example Usage 46 | The API is set up to track simple states of Projects and associated Tasks. 47 | 48 | ## Using curl 49 | ###### Create a project 50 | Creates a project with the name and description supplied in the request. 51 | ``` 52 | curl -H "Content-Type: application/json" -X POST -d '{"name":"My Project", "description":"Project Desc 1"}' http://localhost:8081/projects/create 53 | ``` 54 | 55 | ###### Get Active Projects 56 | Fetches Projects that are not 'Deleted' from the database. 57 | ``` 58 | curl -X GET http://localhost:8081/projects/active 59 | ``` 60 | 61 | ###### Create a Task 62 | Creates a Task with the name and description supplied in the request. 63 | NOTE: `projectId` is an optional parameter. Supplying a `projectId` will 64 | associate the task with a project (The project must already exist). 65 | 66 | After associating a Task with a Project, call the get active projects route. 67 | You will see the Task returned in the Project. 68 | ``` 69 | curl -H "Content-Type: application/json" -X POST -d '{"name":"My Task", "description":"Task 1 Desc", "projectId": 1}' http://localhost:8081/tasks/create 70 | ``` 71 | 72 | ###### Get Active Tasks 73 | Fetches Projects that are not 'Deleted' from the database. 74 | ``` 75 | curl -X GET http://localhost:8081/tasks/active 76 | ``` 77 | # Running Tests 78 | The API is set up to run unit tests using the following commands 79 | ``` 80 | $cd node-express-psql 81 | $npm run test 82 | ``` 83 | 84 | # Architecture 85 | 86 | #### Package Structure 87 | - config - Contains code responsible setup and initialization of components required to run the application. 88 | - models - Contains the [Sequelize] ORM Models for interacting with the database. 89 | - services - Contain the core logic for interacting with models and the databases. Note: The "services" do not take in the request/response objects from the route. The services should have a set and defined list of parameters that it requires. Defining services this way will improve testability by preventing the need to mock requests and responses in unit tests. 90 | - routes - The routes defined in the API. The routes are broken up based on the responsibility of the route. Breaking up the routes will help with readability as the number of routes increases. 91 | - factories - Used to determine which database models should be loaded. Mock models are loaded for unit tests. 92 | 93 | #### Database 94 | For this API Quickstart, Postgres was chosen as the desired database solution. There are many other viable database solutions both relational and non-relational. It is beyond the scope of this Quickstart to discuss the advantages and disadvantages of different database solutions. That said, Postgres is a great relational database solution. 95 | 96 | # Tech 97 | The API relies on a number of technologies. The primary technologies are: 98 | * [NodeJS] - JavaScript Runtime. 99 | * [Express] - Web Application Framework. 100 | * [Sequelize] - ORM for interfacing with the database. Some developers do not like the large amount of abstraction an ORM, like Sequelize, provides. Sequelize offers a strong set of features that can make getting up and running very simple. However, the queries are highly abstracted and Sequelize requires *Sequelize* specific knowledge. It is worth looking at a mid-level query builder solution like the popular [KnexJS]. It offers a strong feature set with less abstraction... 101 | * [Winston] - Logger (Not leveraged nearly enough here, but it is set up for use.) 102 | * [ESlint] - Code linter for keeping the code clean and consistent. 103 | * [Mocha] - Unit test framework. 104 | * [Chai] - Assertion library for unit tests. 105 | * [Sequelize-Mock] - Sequelize Mock is used to mock the database objects for unit tests. NOTE: The setup for Sequelize-Mock varies from the documentation. Factories have been used in this project to import the mock objects rather than overriding the import. 106 | 107 | [KnexJS]: 108 | [Winston]: 109 | [install-node]: 110 | [NodeJS]: 111 | [express]: 112 | [postgress-mac]: 113 | [Sequelize]: 114 | [ESlint]: 115 | [Mocha]: 116 | [Chai]: 117 | [Sequelize-Mock]: 118 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------