Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
medhatelmasry committed Mar 4, 2019
0 parents commit 8138141
Show file tree
Hide file tree
Showing 10 changed files with 295 additions and 0 deletions.
27 changes: 27 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# OS X
.DS_Store*
Icon?
._*

# Windows
Thumbs.db
ehthumbs.db
Desktop.ini

# Linux
.directory
*~


# npm
node_modules
package-lock.json
*.log
*.gz


# Coveralls
coverage

# Benchmarking
benchmarks/graphs
41 changes: 41 additions & 0 deletions app/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// app/app.ts
import express from "express";
import bodyParser from "body-parser";
import { Routes } from "./routes";
import mongoose from 'mongoose';

class App {
public app: express.Application;
public routePrv: Routes = new Routes();

constructor() {
this.app = express();
this.config();
this.routePrv.routes(this.app);
this.mongoSetup();
}

private config(): void{

this.app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
next();
});

// support application/json type post data
this.app.use(bodyParser.json());
//support application/x-www-form-urlencoded post data
this.app.use(bodyParser.urlencoded({ extended: false }));
}

private mongoSetup(): void{
mongoose.connect('mongodb://localhost:27017/school', {})
.then(() => console.log('connection successful'))
.catch((err) => console.error(err));
}

}

export default new App().app;
96 changes: 96 additions & 0 deletions app/controllers/studentController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
// /app/controllers/studentController.ts
import * as mongoose from 'mongoose';
import { StudentSchema } from '../models/student';
import { Request, Response } from 'express';

const StudentMongooseModel = mongoose.model('Student', StudentSchema);

export class StudentController {

public addNewStudent (req: Request, res: Response) {
let newStudent = new StudentMongooseModel(req.body);

newStudent.save((err, data) => {
if (err){
res.send(err);
}
res.json(data);
});
}

public getStudents (req: Request, res: Response) {
StudentMongooseModel.find({}, (err, data) => {
if (err){
res.send(err);
}
res.json(data);
});
}

public getStudentById (req: Request, res: Response) {
StudentMongooseModel.findById(req.params.studentId, (err, data) => {
if (err){
res.send(err);
}
res.json(data);
});
}

public updateStudent (req: Request, res: Response) {
StudentMongooseModel.findOneAndUpdate({ _id: req.params.studentId }, req.body, { new: true },
(err, data) => {
if (err){
res.send(err);
}
res.json(data);
});
}

public deleteStudent (req: Request, res: Response) {
StudentMongooseModel.findOneAndRemove({ _id: req.params.studentId }, (err, data) => {
if (err){
res.send(err);
}
res.json({ message: 'Successfully deleted student!'});
});
}

public generateDummyData (req: Request, res: Response) {
var data = [
{
"FirstName":"Sally",
"LastName":"Baker",
"School":"Mining",
"StartDate": new Date("2012-02-20T08:30:00")
},{
"FirstName":"Jason",
"LastName":"Plumber",
"School":"Engineering",
"StartDate": new Date("2018-03-17T17:32:00")
},{
"FirstName":"Sue",
"LastName":"Gardner",
"School":"Political Science",
"StartDate": new Date("2014-06-20T08:30:00")
},{
"FirstName":"Linda",
"LastName":"Farmer",
"School":"Agriculture",
"StartDate": new Date("2014-06-20T08:30:00")
},{
"FirstName":"Fred",
"LastName":"Fisher",
"School":"Environmental Sciences",
"StartDate": new Date("2017-10-16T17:32:00")
}
];

StudentMongooseModel.collection.insert(data, function (err, docs) {
if (err){
res.send(err);
}
res.json({ message: 'Successfully generated 5 sample documents!'});
});

}
}
24 changes: 24 additions & 0 deletions app/models/student.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// /app/models/student.ts
import mongoose from 'mongoose';

const Schema = mongoose.Schema;

// create a schema
export const StudentSchema = new Schema({
FirstName: {
type: String,
required: true
},
LastName: {
type: String,
required: true
},
School: {
type: String,
required: true
},
StartDate: {
type: Date,
required: true
}
});
40 changes: 40 additions & 0 deletions app/routes/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// /app/routes/index.ts
import {Request, Response} from "express";
import {StudentController} from '../controllers/studentController';

export class Routes {

studentController: StudentController = new StudentController();

public routes(app: any): void {
app.route('/')
.get((req: Request, res: Response) => {
res.status(200).send('Hello Good World!');
});

// Get all students
app.route('/api/students')
.get(this.studentController.getStudents);

// Create a new student
app.route('/api/students')
.post(this.studentController.addNewStudent);

// get a specific student
app.route('/api/students/:studentId')
.get(this.studentController.getStudentById);

// update a specific student
app.route('/api/students/:studentId')
.put(this.studentController.updateStudent);

// delete a specific student
app.route('/api/students/:studentId')
.delete(this.studentController.deleteStudent);

// generate dummy data
app.route('/api/dummy')
.get(this.studentController.generateDummyData);

}
}
7 changes: 7 additions & 0 deletions app/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// app/server.ts
import app from "./app";
const port = process.env.PORT || 3000;

app.listen(port, () => {
console.log(`'Express server listening on port ${port}!`);
})
14 changes: 14 additions & 0 deletions build/app.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions build/app.js.map

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

25 changes: 25 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"name": "tsexpress",
"version": "1.0.0",
"description": "",
"main": "build/server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"tsc": "tsc",
"dev": "ts-node-dev --respawn --transpileOnly ./app/server.ts",
"prod": "tsc && node ./build/server.js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"ts-node-dev": "^1.0.0-pre.32",
"typescript": "^3.3.3333"
},
"dependencies": {
"@types/express": "^4.16.1",
"@types/mongoose": "^5.3.20",
"body-parser": "^1.18.3",
"express": "^4.16.4",
"mongoose": "^5.4.17"
}
}
20 changes: 20 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"compilerOptions": {
/* Basic Options */
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
"sourceMap": true, /* Generates corresponding '.map' file. */
"outDir": "./build", /* Redirect output structure to the directory. */
"strict": true, /* Enable all strict type-checking options. */
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
"baseUrl": "./app", /* Base directory to resolve non-absolute module names. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
},
"include": [
"app/**/*.ts"
],
"exclude": [
"node_modules"
]

}

0 comments on commit 8138141

Please sign in to comment.