generated from actions/javascript-action
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdatastore.js
43 lines (32 loc) · 1.16 KB
/
datastore.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
const fs = require('fs');
const path = require('path');
const { Datastore } = require('@google-cloud/datastore');
class WrongMethodError extends Error {}
const credentialsPath = path.join(__dirname, 'credentials.json');
const setupCredentials = async (base64ServiceAccount) => {
const serviceAccountBuffer = Buffer.from(base64ServiceAccount, 'base64');
const writeCredentialsPromise = new Promise((resolve, reject) => {
fs.writeFile(credentialsPath, serviceAccountBuffer, (err) => {
if (err) {
reject(err);
}
resolve(credentialsPath);
});
});
return await writeCredentialsPromise;
};
const setEntity = async (projectId, action, kind, name, jsonData) => {
const datastore = new Datastore({ projectId, keyFilename: credentialsPath });
const data = JSON.parse(jsonData);
const key = datastore.key([kind, name]);
const entity = { key, data };
if (action === 'save') {
await datastore.save(entity);
} else if (action == 'merge') {
await datastore.merge(entity);
} else {
throw new WrongMethodError();
}
return entity;
};
module.exports = { credentialsPath, setupCredentials, setEntity, WrongMethodError };