Skip to content

Instantly share code, notes, and snippets.

@cristianounix
Created July 22, 2015 01:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cristianounix/f988befba5f7ff626b63 to your computer and use it in GitHub Desktop.
Save cristianounix/f988befba5f7ff626b63 to your computer and use it in GitHub Desktop.
simple-api-beer
var http = require("http");
var fs = require("fs");
var index = fs.readFileSync("index.html");
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
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() }
}
, BeerSchema = new Schema(_schema)
, Beer = mongoose.model('Beer', BeerSchema)
;
var query = {}
, msg;
http.createServer(function(request, response) {
response.writeHead(200,{"Content-Type": "text/html"});
var url = request.url;
switch(url){
case '/create':
var dados = {
name: 'Heineken',
description: 'Até q eh boazinha',
alcohol: 5.5,
price: 3.5,
category: 'lager'
}
var model = new Beer(dados);
model.save(function (err, data) {
if (err){
msg = JSON.stringify(err);
}
else{
msg = JSON.stringify(data);
}
});
break;
case '/get':
Beer.find(query, function (err, data) {
if (err){
msg = JSON.stringify(err);
} else{
msg = JSON.stringify(data);
}
});
break;
case '/update':
break;
case '/delete':
var query = {name: /brahma/i};
Beer.remove(query, function (err, data) {
if (err){
msg = JSON.stringify(err);
} else{
msg = JSON.stringify(data);
}
});
break;
}
if(url == '/'){
}
Beer.find(query, function (err, data) {
if (err){
console.log('Erro: ', err);
msg = JSON.stringify(err);
}
else{
console.log('Cerveja deletada com sucesso', data.result);
msg = JSON.stringify(data);
}
response.end(msg);
});
}).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