source out rest-functions from app.js into other js.files

23 views
Skip to first unread message

dukehh

unread,
Dec 11, 2016, 12:00:34 PM12/11/16
to nodejs
hi,
ii am new with nodejs.i habe worked on an utube-example  from Brad Traversy, bookstore. I would like to source the rest.functions out from app.js (see snippet below) into stand-alone files like   genreRest.js, bookRest.js, or further (customer, store,..). i tried with module.exports und require but obviously i dint manage. Can anybody give me a hint how to extract the rest-functions from app.js into standalone js-files, for example the genre-REstfunctions below?

thanx a lot for helping.
dukehh

app.js:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

app.use(bodyParser.json());

Genre = require('./models/genre');
Book = require('./models/book');

//Connect to mongoose
mongoose.connect('mongodb://localhost/bookstore');
var db = mongoose.connection;

app.get('/', function(req, res){
res.send('Please use /api/books or /api/genres');
});

// Get Genres
app.get('/api/genres', function(req, res){
Genre.getGenres(function (err, genres) {
// body...
if(err){
throw err;
}
res.json(genres);
});
});

// Add Genre
...

// Get Books
app.get('/api/books', function(req, res){
Book.getBooks(function (err, books) {
// body...
if(err){
throw err;
}
res.json(books);
});
});

// Get Book by ID
...

// Add Books
...


app.listen(3000);
...

Muhammad Wasim

unread,
Dec 16, 2016, 11:21:05 PM12/16/16
to nod...@googlegroups.com
HI,

You can easily do it using app.use functions.


in app.js add following:
var genre = require('genre.js');
app.use('/api/genres',genre);


in genre.js file:
// Get Genres
app.get('/', function(req, res){
Genre.getGenres(function (err, genres) {
// body...
if(err){
throw err;
}
res.json(genres);
});
});

// Add Genre
...


regards,
Muhammad Wasim

--
Job board: http://jobs.nodejs.org/
New group rules: https://gist.github.com/othiym23/9886289#file-moderation-policy-md
Old group rules: https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
---
You received this message because you are subscribed to the Google Groups "nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email to nodejs+unsubscribe@googlegroups.com.
To post to this group, send email to nod...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/nodejs/01f7c2fb-7e23-4fca-b934-b70e4075f2a2%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Regards,
Muhammad Wasim | Lead Software Engineer | Zigron Inc.
E-mail: muhamma...@zigron.com
Website: www.zigron.com
Reply all
Reply to author
Forward
0 new messages