Skip to content

Instantly share code, notes, and snippets.

@suissa
Created July 22, 2015 01:31
Show Gist options
  • Save suissa/053ae746dd257781ceb3 to your computer and use it in GitHub Desktop.
Save suissa/053ae746dd257781ceb3 to your computer and use it in GitHub Desktop.
Servidor com rotas manuais em Node.js
var http = require('http');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/workshop-online-julho-2015');
var db = mongoose.connection;
db.on('error', function(err){
console.log('Erro de conexao.', err);
});
db.on('open', function () {
console.log('Conexão aberta.');
});
db.on('connected', function(err){
console.log('Conectado');
});
db.on('disconnected', function(err){
console.log('Desconectado');
});
var Schema = mongoose.Schema
, _schema = {
name: { type: String, default: '' }
, description: { type: String, default: '' }
, alcohol: { type: Number, min: 0, default: '' }
, price: { type: Number, min: 0, default: '' }
, category: { type: String, default: ''}
, created_at: { type: Date, default: Date.now() }
}
, ModelSchema = new Schema(_schema)
, Model = mongoose.model('Beer', ModelSchema)
;
var query = {}
, msg = ""
, Controller = {
create: function(req, res) {
var dados = {
name: 'Heineken',
description: 'Até q eh boazinha',
alcohol: 5.5,
price: 3.5,
category: 'lager'
}
var model = new Model(dados);
model.save(function (err, data) {
if (err){
console.log('Erro: ', err);
msg = JSON.stringify(err);
}
else{
console.log('Sucesso:', data);
msg = JSON.stringify(data);
}
res.end(msg);
});
}
, retrieve: function(req, res) {
Model.find(query, function (err, data) {
if (err){
console.log('Erro: ', err);
msg = JSON.stringify(err);
}
else{
console.log('Sucesso:', data);
msg = JSON.stringify(data);
}
res.end(msg);
});
}
, update: function(req, res) {
query = {name: /heineken/i};
var mod = {
name: 'Brahma'
, alcohol: 4
, price: 6
}
;
Model.update(query, mod, function (err, data) {
if (err){
console.log('Erro: ', err);
msg = JSON.stringify(err);
}
else{
console.log('Sucesso:', data);
msg = JSON.stringify(data);
}
res.end(msg);
});
}
, delete: function(req, res) {
query = {name: /brahma/i};
Model.remove(query, function (err, data) {
if (err){
console.log('Erro: ', err);
msg = JSON.stringify(err);
}
else{
console.log('Sucesso:', data);
msg = JSON.stringify(data);
}
res.end(msg);
});
}
}
;
http.createServer(function(req, res) {
var url = req.url;
switch(url){
case '/api/beers/create':
Controller.create(req, res);
break;
case '/api/beers/retrieve':
Controller.retrieve(req, res);
break;
case '/api/beers/update':
Controller.update(req, res);
break;
case '/api/beers/delete':
Controller.delete(req, res);
break;
default: res.end('Rota não encontrada');
}
}).listen(3000);
console.log('Entre em http://localhost:3000/');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment