forked from GoogleCloudPlatform/nodejs-docs-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
62 lines (53 loc) · 1.68 KB
/
app.js
File metadata and controls
62 lines (53 loc) · 1.68 KB
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
// Copyright 2019 Google LLC. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
// [START run_imageproc_controller]
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
const image = require('./image');
app.post('/', async (req, res) => {
if (!req.body) {
const msg = 'no Pub/Sub message received';
console.error(`error: ${msg}`);
res.status(400).send(`Bad Request: ${msg}`);
return;
}
if (!req.body.message || !req.body.message.data) {
const msg = 'invalid Pub/Sub message format';
console.error(`error: ${msg}`);
res.status(400).send(`Bad Request: ${msg}`);
return;
}
// Decode the Pub/Sub message.
const pubSubMessage = req.body.message;
let data;
try {
data = Buffer.from(pubSubMessage.data, 'base64').toString().trim();
data = JSON.parse(data);
} catch (err) {
const msg =
'Invalid Pub/Sub message: data property is not valid base64 encoded JSON';
console.error(`error: ${msg}: ${err}`);
res.status(400).send(`Bad Request: ${msg}`);
return;
}
// Validate the message is a Cloud Storage event.
if (!data.name || !data.bucket) {
const msg =
'invalid Cloud Storage notification: expected name and bucket properties';
console.error(`error: ${msg}`);
res.status(400).send(`Bad Request: ${msg}`);
return;
}
try {
await image.blurOffensiveImages(data);
res.status(204).send();
} catch (err) {
console.error(`error: Blurring image: ${err}`);
res.status(500).send();
}
});
// [END run_imageproc_controller]
module.exports = app;