-
Notifications
You must be signed in to change notification settings - Fork 0
/
image.js
62 lines (50 loc) · 1.58 KB
/
image.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
var image = exports; exports.constructor = function image(){};
var mysql = require('mysql');
var async = require('async');
var path = require('path');
var fs = require('fs');
var DBG = (process.env.DEBUG) ? console.log : false;
var dbClient = mysql.createClient({
"host":"localhost",
"port": 3306,
"image":"goinstant",
"password":"",
"database":"haggle"
});
// GET (id) - Retrieve the data instance referenced by id
image.get = function(req, res) {
var id = req.params.id;
DBG&&DBG("GET - id:", id);
res.sendfile(__dirname + "/upload_images/" + id + ".jpg", function(err) {
if(err) return res.json({ 'err': new Error("Image not found"), 'response': null }, 500);
});
};
// POST - Add a new image to the db
image.post = function(req, res) {
DBG&&DBG("POST:");
var body = "";
req.on('data', function(chunk) {
body += chunk;
});
req.on('end', function() {
try {
DBG&&DBG("POST");
DBG&&DBG(" body: " + body);
var image = JSON.parse(body);
dbClient.query("INSERT INTO image", function(err, results) {
var imageId = results.insertId;
if (err || !imageId) {
DBG&&DBG("Error creating image");
DBG&&DBG(err);
return res.json(new Error("Server error: could not create new image"), 500);
}
fs.writeFile("/images/" + imageId + ".jpg", body, function(err) {
if(err) return res.json(err, 500);
return res.json({ 'err': null, 'response': { 'id': imageId } });
});
});
} catch(err) {
return res.json({ 'err': err }, 500);
}
});
};