Skip to content
Snippets Groups Projects
Commit a833039a authored by Andrej Rasevic's avatar Andrej Rasevic
Browse files

adding express examples

parent e2adb048
No related branches found
No related tags found
No related merge requests found
Showing
with 5885 additions and 0 deletions
node_modules
\ No newline at end of file
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mongoose = require('mongoose');
var indexRouter = require('./routes/index');
var authorsRouter = require('./routes/api/v1/authors');
var bodyParser = require('body-parser');
var app = express();
app.use(logger('dev'));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use('/', indexRouter);
app.use('/api/v1/authors', authorsRouter);
//connect mongoose
// store credentials as enviroment variables
//const dbuser = process.env.MONGODB
//const dbpass = process.env.MONGODBPASS
const dbuser = 'dbadmin'
const dbpass = 'dbpassword'
// TODO - Discuss connection uri
// Need to set mongoDB variable to the uri for your own database
// explain what lectureExamples is in the url and show on Atlas
const mongoDB = 'mongodb://localhost/lectureExamples?retryWrites=true';
mongoose.connect(mongoDB, { useNewUrlParser: true, useUnifiedTopology: true });
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
module.exports = app;
\ No newline at end of file
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('apiexample:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
var Author = require('../models/author');
// Retrieve list of all Authors.
exports.author_list = function(req, res) {
Author.find({}, (err, authors) => {
res.json(authors)
})
};
// Retrieve detail info for a specific Author.
exports.author_detail = function(req, res) {
//querying the database for a author that matches the authorID parameter from the URL request
// Author.findById(req.params.authorId, (err, author) => {
// res.json(author)
// when using middleware
res.json(req.author)
//})
};
// Handle Author create on POST.
exports.author_create_post = function(req, res) {
let author = new Author(req.body);
//Need this for persistance
author.save();
res.status(201).send(author)
};
// Handle Author delete on DELETE.
exports.author_delete = function(req, res) {
Author.findById(req.params.authorId, (err, author) => {
// with middleware
// req.author.remove(err => {
author.remove(err => {
if(err){
res.status(500).send(err)
}
else{
res.status(204).send('removed')
}
})
})
};
/* Right way to do an update as PUT*/
exports.author_update = function(req, res) {
Author.findByIdAndUpdate(req.params.authorId,{$set:req.body},{new: true}, function(err, result){
if(err){
console.log('error in put');
console.log(err);
}
console.log("RESULT: " + result);
res.json(result);
});
};
\ No newline at end of file
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// Defines what individual author document looks like
var AuthorSchema = new Schema(
{
firstName: {type: String, required: true, max: 100},
familyName: {type: String, required: true, max: 100},
dateOfBirth: {type: Date},
dateOfDeath: {type: Date},
}
);
//Export model - compiles a model
// instances of models are called documents
module.exports = mongoose.model('Author', AuthorSchema);
//The first argument is the singular name of the collection your model is for.
//Mongoose automatically looks for the plural, lowercased version of your model name.
//Thus, for the example above, the model Author is for the authors collection in the database.
\ No newline at end of file
This diff is collapsed.
{
"name": "apiexample",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www",
"devstart": "nodemon ./bin/www"
},
"dependencies": {
"async": "^2.6.2",
"cookie-parser": "~1.4.3",
"debug": "~2.6.9",
"express": "~4.16.0",
"mongoose": "^5.13.1",
"morgan": "~1.9.0"
},
"devDependencies": {
"nodemon": "^1.18.10"
}
}
#! /usr/bin/env node
console.log('This script populates some test books, authors, genres and bookinstances to your database. Specified database as argument - e.g.: populatedb mongodb+srv://cooluser:coolpassword@cluster0-mbdj7.mongodb.net/local_library?retryWrites=true');
// Get arguments passed on command line
var userArgs = process.argv.slice(2);
/*
if (!userArgs[0].startsWith('mongodb')) {
console.log('ERROR: You need to specify a valid mongodb URL as the first argument');
return
}
*/
var async = require('async')
var Book = require('./models/book')
var Author = require('./models/author')
var Genre = require('./models/genre')
var BookInstance = require('./models/bookinstance')
var mongoose = require('mongoose');
var mongoDB = userArgs[0];
mongoose.connect(mongoDB, { useNewUrlParser: true });
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
var authors = []
var genres = []
var books = []
var bookinstances = []
function authorCreate(first_name, family_name, d_birth, d_death, cb) {
authordetail = {first_name:first_name , family_name: family_name }
if (d_birth != false) authordetail.date_of_birth = d_birth
if (d_death != false) authordetail.date_of_death = d_death
var author = new Author(authordetail);
author.save(function (err) {
if (err) {
cb(err, null)
return
}
console.log('New Author: ' + author);
authors.push(author)
cb(null, author)
} );
}
function genreCreate(name, cb) {
var genre = new Genre({ name: name });
genre.save(function (err) {
if (err) {
cb(err, null);
return;
}
console.log('New Genre: ' + genre);
genres.push(genre)
cb(null, genre);
} );
}
function bookCreate(title, summary, isbn, author, genre, cb) {
bookdetail = {
title: title,
summary: summary,
author: author,
isbn: isbn
}
if (genre != false) bookdetail.genre = genre
var book = new Book(bookdetail);
book.save(function (err) {
if (err) {
cb(err, null)
return
}
console.log('New Book: ' + book);
books.push(book)
cb(null, book)
} );
}
function bookInstanceCreate(book, imprint, due_back, status, cb) {
bookinstancedetail = {
book: book,
imprint: imprint
}
if (due_back != false) bookinstancedetail.due_back = due_back
if (status != false) bookinstancedetail.status = status
var bookinstance = new BookInstance(bookinstancedetail);
bookinstance.save(function (err) {
if (err) {
console.log('ERROR CREATING BookInstance: ' + bookinstance);
cb(err, null)
return
}
console.log('New BookInstance: ' + bookinstance);
bookinstances.push(bookinstance)
cb(null, book)
} );
}
function createGenreAuthors(cb) {
async.series([
function(callback) {
authorCreate('Patrick', 'Rothfuss', '1973-06-06', false, callback);
},
function(callback) {
authorCreate('Ben', 'Bova', '1932-11-8', false, callback);
},
function(callback) {
authorCreate('Isaac', 'Asimov', '1920-01-02', '1992-04-06', callback);
},
function(callback) {
authorCreate('Bob', 'Billings', false, false, callback);
},
function(callback) {
authorCreate('Jim', 'Jones', '1971-12-16', false, callback);
},
function(callback) {
genreCreate("Fantasy", callback);
},
function(callback) {
genreCreate("Science Fiction", callback);
},
function(callback) {
genreCreate("French Poetry", callback);
},
],
// optional callback
cb);
}
function createBooks(cb) {
async.parallel([
function(callback) {
bookCreate('The Name of the Wind (The Kingkiller Chronicle, #1)', 'I have stolen princesses back from sleeping barrow kings. I burned down the town of Trebon. I have spent the night with Felurian and left with both my sanity and my life. I was expelled from the University at a younger age than most people are allowed in. I tread paths by moonlight that others fear to speak of during day. I have talked to Gods, loved women, and written songs that make the minstrels weep.', '9781473211896', authors[0], [genres[0],], callback);
},
function(callback) {
bookCreate("The Wise Man's Fear (The Kingkiller Chronicle, #2)", 'Picking up the tale of Kvothe Kingkiller once again, we follow him into exile, into political intrigue, courtship, adventure, love and magic... and further along the path that has turned Kvothe, the mightiest magician of his age, a legend in his own time, into Kote, the unassuming pub landlord.', '9788401352836', authors[0], [genres[0],], callback);
},
function(callback) {
bookCreate("The Slow Regard of Silent Things (Kingkiller Chronicle)", 'Deep below the University, there is a dark place. Few people know of it: a broken web of ancient passageways and abandoned rooms. A young woman lives there, tucked among the sprawling tunnels of the Underthing, snug in the heart of this forgotten place.', '9780756411336', authors[0], [genres[0],], callback);
},
function(callback) {
bookCreate("Apes and Angels", "Humankind headed out to the stars not for conquest, nor exploration, nor even for curiosity. Humans went to the stars in a desperate crusade to save intelligent life wherever they found it. A wave of death is spreading through the Milky Way galaxy, an expanding sphere of lethal gamma ...", '9780765379528', authors[1], [genres[1],], callback);
},
function(callback) {
bookCreate("Death Wave","In Ben Bova's previous novel New Earth, Jordan Kell led the first human mission beyond the solar system. They discovered the ruins of an ancient alien civilization. But one alien AI survived, and it revealed to Jordan Kell that an explosion in the black hole at the heart of the Milky Way galaxy has created a wave of deadly radiation, expanding out from the core toward Earth. Unless the human race acts to save itself, all life on Earth will be wiped out...", '9780765379504', authors[1], [genres[1],], callback);
},
function(callback) {
bookCreate('Test Book 1', 'Summary of test book 1', 'ISBN111111', authors[4], [genres[0],genres[1]], callback);
},
function(callback) {
bookCreate('Test Book 2', 'Summary of test book 2', 'ISBN222222', authors[4], false, callback)
}
],
// optional callback
cb);
}
function createBookInstances(cb) {
async.parallel([
function(callback) {
bookInstanceCreate(books[0], 'London Gollancz, 2014.', false, 'Available', callback)
},
function(callback) {
bookInstanceCreate(books[1], ' Gollancz, 2011.', false, 'Loaned', callback)
},
function(callback) {
bookInstanceCreate(books[2], ' Gollancz, 2015.', false, false, callback)
},
function(callback) {
bookInstanceCreate(books[3], 'New York Tom Doherty Associates, 2016.', false, 'Available', callback)
},
function(callback) {
bookInstanceCreate(books[3], 'New York Tom Doherty Associates, 2016.', false, 'Available', callback)
},
function(callback) {
bookInstanceCreate(books[3], 'New York Tom Doherty Associates, 2016.', false, 'Available', callback)
},
function(callback) {
bookInstanceCreate(books[4], 'New York, NY Tom Doherty Associates, LLC, 2015.', false, 'Available', callback)
},
function(callback) {
bookInstanceCreate(books[4], 'New York, NY Tom Doherty Associates, LLC, 2015.', false, 'Maintenance', callback)
},
function(callback) {
bookInstanceCreate(books[4], 'New York, NY Tom Doherty Associates, LLC, 2015.', false, 'Loaned', callback)
},
function(callback) {
bookInstanceCreate(books[0], 'Imprint XXX2', false, false, callback)
},
function(callback) {
bookInstanceCreate(books[1], 'Imprint XXX3', false, false, callback)
}
],
// Optional callback
cb);
}
async.series([
createGenreAuthors,
createBooks,
createBookInstances
],
// Optional callback
function(err, results) {
if (err) {
console.log('FINAL ERR: '+err);
}
else {
console.log('BOOKInstances: '+bookinstances);
}
// All done, disconnect from database
mongoose.connection.close();
});
\ No newline at end of file
<html>
<head>
<title>Express</title>
<link rel="stylesheet" href="/stylesheets/style.css">
</head>
<body>
<h1>Express</h1>
<p>Welcome to Express</p>
</body>
</html>
body {
padding: 50px;
font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;
}
a {
color: #00B7FF;
}
var express = require('express');
var authorRouter = express.Router();
var Author = require('../../../models/author')
// Require controller modules.
var author_controller = require('../../../controllers/authorController');
//Note: the middleware defined in this file are referred to as
//router-level middleware
// a middleware function with no mount path. This code is executed for every request to the router
authorRouter.use(function (req, res, next) {
console.log('Time:', Date.now())
next()
})
authorRouter.use('/', (req, res, next)=>{
console.log("I run first before I retrieve all the authors")
//Request vs Params parameters
//If you want to identify a resource, you should use Path Variable.
// But if you want to sort or filter items, then you should use query parameter.
for (const key in req.query) {
console.log(key, req.query[key])
}
next()
})
authorRouter.use('/:authorId', (req, res, next) => {
Author.findById( req.params.authorId, (err,author) => {
if(err)
res.status(500).send(err)
else {
// append to request object new property-value pair from db
req.author = author;
next()
}
})
})
authorRouter.route('/')
.get(author_controller.author_list)
.post(author_controller.author_create_post);
authorRouter.route('/:authorId')
.get(author_controller.author_detail)
.delete(author_controller.author_delete)
authorRouter.route('/:authorId/update')
.put(author_controller.author_update)
module.exports = authorRouter;
\ No newline at end of file
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
node_modules
.DS_Store
\ No newline at end of file
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mongoose = require('mongoose');
var indexRouter = require('./routes/index');
var authorsRouter = require('./routes/api/v1/authors');
var bodyParser = require('body-parser');
const expressValidator = require('express-validator');
var app = express();
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.json());
app.use(expressValidator());
app.use('/', indexRouter);
app.use('/api/v1/authors', authorsRouter);
//connect mongoose
// TODO - Discuss connection uri
// Need to set mongoDB variable to the uri for your own database
const mongoDB = 'mongodb://localhost/lectureExamples?retryWrites=true';
mongoose.connect(mongoDB, { useNewUrlParser: true, useUnifiedTopology: true });
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
module.exports = app;
\ No newline at end of file
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('apiexample:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
var Author = require('../models/author');
const { body } = require('express-validator/check')
const { validationResult } = require('express-validator/check');
// Retrieve list of all Authors.
exports.author_list = function(req, res) {
Author.find({}, (err, authors) => {
res.json(authors)
})
};
// Retrieve detail info for a specific Author.
exports.author_detail = function(req, res) {
//querying the database for a author that matches the authorID parameter from the URL request
// Author.findById(req.params.authorId, (err, author) => {
// res.json(author)
// when using middleware
res.json(req.author)
//})
};
// Handle Author create on POST.
exports.author_create_post = async (req, res, next) => {
//let author = new Author(req.body);
//Need this for persistance
//author.save();
//res.status(201).send(author)
try {
const errors = validationResult(req); // Finds the validation errors in this request and wraps them in an object with handy functions
if (!errors.isEmpty()) {
console.log(errors)
res.status(422).json({ errors: errors.array() });
return;
}
const { firstName, familyName, dateOfBirth, dateOfDeath } = req.body
const author = await Author.create({
firstName,
familyName,
dateOfBirth,
dateOfDeath,
})
res.json(author)
} catch(err) {
return next(err)
}
};
// Handle Author delete on DELETE.
exports.author_delete = function(req, res) {
Author.findById(req.params.authorId, (err, author) => {
// with middleware
// req.author.remove(err => {
author.remove(err => {
if(err){
res.status(500).send(err)
}
else{
res.status(204).send('removed')
}
})
})
};
/* Right way to do an update as PUT*/
exports.author_update = function(req, res) {
Author.findByIdAndUpdate(req.params.authorId,{$set:req.body},{new: true}, function(err, result){
if(err){
console.log('error in put');
console.log(err);
}
console.log("RESULT: " + result);
res.json(result);
});
};
exports.validate = (method) => {
switch (method) {
case 'author_create_post': {
console.log('validating author')
return [
body('firstName', 'firstName doesn\'t exist').exists(),
body('familyName', 'famlyName doesn\'t exist').exists()
]
}
}
}
\ No newline at end of file
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// Defines what individual author document looks like
var AuthorSchema = new Schema(
{
firstName: {type: String, max: 100},
familyName: {type: String, max: 100},
dateOfBirth: {type: Date},
dateOfDeath: {type: Date},
}
);
//Export model - compiles a model
// instances of models are called documents
module.exports = mongoose.model('Author', AuthorSchema);
//The first argument is the singular name of the collection your model is for.
//Mongoose automatically looks for the plural, lowercased version of your model name.
//Thus, for the example above, the model Author is for the authors collection in the database.
\ No newline at end of file
This diff is collapsed.
{
"name": "apiexample",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www",
"devstart": "nodemon ./bin/www"
},
"dependencies": {
"async": "^2.6.2",
"cookie-parser": "~1.4.3",
"debug": "~2.6.9",
"express": "~4.16.0",
"express-validator": "^5.3.1",
"mongoose": "^5.13.1",
"morgan": "~1.9.0"
},
"devDependencies": {
"nodemon": "^1.18.10"
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment