Last active
December 16, 2021 11:44
-
-
Save fragaLY/cdd42159ca96dedd4ee6a3b3605954f1 to your computer and use it in GitHub Desktop.
Google Cloud Datastore and Node.js example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const config = require('../config'); | |
const Datastore = require("@google-cloud/datastore"); | |
const datastore = Datastore({ | |
projectId: config.get('GCLOUD_PROJECT') | |
}); | |
const kind = 'Question'; | |
function create({ | |
quiz, | |
author, | |
title, | |
answer1, | |
answer2, | |
answer3, | |
answer4, | |
correctAnswer | |
}) { | |
const key = datastore.key(kind); | |
const entity = { | |
key, | |
data: [{ | |
name: 'quiz', | |
value: quiz | |
}, | |
{ | |
name: 'author', | |
value: author | |
}, | |
{ | |
name: 'title', | |
value: title | |
}, | |
{ | |
name: 'answer1', | |
value: answer1 | |
}, | |
{ | |
name: 'answer2', | |
value: answer2 | |
}, | |
{ | |
name: 'answer3', | |
value: answer3 | |
}, | |
{ | |
name: 'answer4', | |
value: answer4 | |
}, | |
{ | |
name: 'correctAnswer', | |
value: correctAnswer | |
}, | |
] | |
}; | |
return datastore.save(entity); | |
} | |
function list(quiz = 'gcp', redact = true) { | |
const query = datastore.createQuery([kind]).filter('quiz', '=', quiz); | |
const result = datastore.runQuery(query); | |
return result.then(([results, { moreResults, endCursor }]) => { | |
const questions = results.map(item => { | |
item.id = item[Datastore.KEY].id; | |
if (redact) { | |
delete item.correctAnswer; | |
} | |
return item; | |
}); | |
return { | |
questions, | |
nextPageToken: moreResults != 'NO_MORE_RESULTS' ? endCursor : false | |
}; | |
}); | |
} | |
module.exports = { | |
create, | |
list | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment