-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathapp.js
101 lines (90 loc) · 2.52 KB
/
app.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
const VisualRecognitionV3 = require('ibm-watson/visual-recognition/v3');
const path = require('path');
const express = require('express');
const app = express();
const fs = require('fs');
const uuid = require('uuid');
const os = require('os');
require('./config/express')(app);
/**
* Parse a base 64 image and return the extension and buffer
* @param {String} imageString The image data as base65 string
* @return {Object} { type: String, data: Buffer }
*/
const parseBase64Image = (imageString) => {
const matches = imageString.match(/^data:image\/([A-Za-z-+/]+);base64,(.+)$/);
const resource = {};
if (matches.length !== 3) {
return null;
}
resource.type = matches[1] === 'jpeg' ? 'jpg' : matches[1];
resource.data = new Buffer(matches[2], 'base64');
return resource;
};
let client;
try {
client = new VisualRecognitionV3({
// Remember to place the credentials in the .env file. Read the README.md file!
version: '2018-03-19',
});
} catch (err) {
console.error('Error creating service client: ', err);
}
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
app.get('/health', (req, res) => {
res.json({ status: 'UP' });
});
app.post('/api/classify', async (req, res, next) => {
let imageFile;
let temp
if (req.body.image_file) {
imageFile = fs.createReadStream(`public/${req.body.image_file}`);
}
else if (req.body.image_data) {
try {
const resource = parseBase64Image(req.body.image_data);
temp = path.join(os.tmpdir(), `${uuid.v4()}.${resource.type}`);
fs.writeFileSync(temp, resource.data);
imageFile = fs.createReadStream(temp);
} catch (err) {
console.error('Error creating image file: ', err);
next(err);
return;
}
}
const classifyParams = {
imagesFile: imageFile,
classifierIds: ['default']
};
try {
const response = await client.classify(classifyParams);
res.json(response);
} catch(err) {
console.error(err);
if (!client) {
const error = {
title: 'Invalid credentials',
description:
'Could not find valid credentials for the Visual Recognition service.',
statusCode: 401,
};
next(error);
}
next(err);
} finally {
if (temp) {
fs.unlink(temp, (err) => {
if (err) {
console.error(err)
return
}
//file removed
})
}
}
});
// error-handler settings for all other routes
require('./config/error-handler')(app);
module.exports = app;