Skip to content

Instantly share code, notes, and snippets.

@houtianze
Created April 6, 2017 12:33
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 houtianze/e624d5588988f85e09bc2874c4cea255 to your computer and use it in GitHub Desktop.
Save houtianze/e624d5588988f85e09bc2874c4cea255 to your computer and use it in GitHub Desktop.
Cart
'use strict';
// Code not verified / tested though. -Tianze
var express = require("express");
var fs = require("fs");
var _ = require("underscore");
var dbJsonFileName = "carts.json";
var dbJson = fs.readFileSync(dbJsonFileName, 'utf8');
var app = express();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
function saveDb() {
fs.writeFile(dbJsonFileName, dbJson);
}
app.get("/carts", function(req, res) {
res.send(dbJson);
});
app.get("/carts/:id", function(req, res) {
var id = req.params.id;
dbJson.forEach(function(item) {
if (item.id === id) {
res.send(item);
return;
}
});
res.status(404).send();
});
app.post("/carts", function(req, res) {
dbJson = req.body;
saveDb();
});
app.put("/carts/:id", function(req, res) {
var id = req.params.id;
dbJson.forEach(function(item, index, arr) {
if (item.id === id) {
arr[index] = req.body;
saveDb();
res.send();
return;
}
});
res.status(404).send();
});
app.delete("/carts/:id", function(req, res) {
var id = req.params.id;
dbJson.forEach(function(item, index, arr) {
if (item.id === id) {
arr.splice(index, 1);
saveDb();
res.send();
return;
}
});
res.status(404).send();
});
var port = process.env.PORT || 3000;
app.listen(port, function () {
console.log("To view your app, open this link in your browser: http://localhost:" + port);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment