This repository has been archived by the owner on Apr 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
69 lines (55 loc) · 1.65 KB
/
index.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
import { Datastore } from '@google-cloud/datastore';
const VIEW_KIND = 'view';
const BAD_REQUEST = 400;
const SERVER_ERROR = 500;
const datastore = new Datastore();
export async function viewcounter(request, response) {
// CORS headers
response.set('Access-Control-Allow-Origin', '*');
response.set('Access-Control-Allow-Methods', 'GET');
const href = request.body;
// empty request sends an empty object as the body
if (!href || typeof href === 'object' || href.length === 0) {
return response.status(BAD_REQUEST).json({
message: 'href post body data is missing!',
});
}
if (href.indexOf('deploy-preview') > -1) {
return response.json({ preview: true });
}
if (href.indexOf('gis.utah.gov') === -1 && process.env.NODE_ENV === 'production') {
return response.json({ skip: true, NODE_ENV: `${process.env.NODE_ENV}` });
}
const key = datastore.key([VIEW_KIND, href]);
const [entity] = await datastore.get(key);
if (!entity) {
const data = { count: 1 };
try {
await datastore.save({
key,
data,
});
} catch (error) {
return response.status(SERVER_ERROR).json({
message: 'error creating record',
error: error || '',
});
}
console.log('record created successfully');
return response.json(data);
}
entity.count++;
try {
await datastore.save({
key,
data: { count: entity.count },
});
} catch (error) {
return response.status(SERVER_ERROR).json({
message: 'error updating record',
error: error || '',
});
}
console.log('record updated successfully');
return response.json({ count: entity.count });
};