firestore_create_rest.js
#! /usr/bin/node
// ---------------------------------------------------------------
// firestore_create_rest.js
//
// Feb/01/2020
//
// ---------------------------------------------------------------
var fs = require("fs")
var get_token = require('./get_token.js')
// ---------------------------------------------------------------
function patch_proc(client,token,url,str_json)
{
const args = {
data: str_json,
headers: { "Authorization": "Bearer " + token}
}
try
{
client.patch(url, args, function (data, response) {
console.log(data)
})
}
catch (error)
{
console.error ("*** error *** from client.get ***")
console.error (error)
}
}
// ---------------------------------------------------------------
function add_data_proc(client,token,url_base,key,name,population,date_mod)
{
var data = {}
unit_aa = {}
unit_aa['name'] = {"stringValue": ""}
unit_aa['population'] = {"integerValue": 0}
unit_aa['date_mod'] = {"stringValue": ""}
data['fields'] = unit_aa
data.fields.name.stringValue = name
data.fields.population.integerValue = population
data.fields.date_mod.stringValue = date_mod
const str_json = JSON.stringify(data)
const url = url_base + key
patch_proc(client,token,url,str_json)
}
// ---------------------------------------------------------------
console.error ("*** 開始 ***")
const env = process.env
const json_str = fs.readFileSync (env.GOOGLE_APPLICATION_CREDENTIALS,'utf8')
const dict_aa = JSON.parse (json_str)
const project_id = dict_aa['project_id']
console.log(project_id)
const token = get_token.get_token_proc()
const project = 'project-jan25-2020'
const url_base="https://firestore.googleapis.com/v1/projects/" + project_id + "/databases/(default)/documents/cities/"
var Client = require('node-rest-client').Client
var client = new Client()
add_data_proc(client,token,url_base,'t0921','宇都宮',81236,'1954-9-24')
add_data_proc(client,token,url_base,'t0922','小山',94247,'1954-2-15')
add_data_proc(client,token,url_base,'t0923','佐野',71393,'1954-5-28')
add_data_proc(client,token,url_base,'t0924','足利',35441,'1954-7-8')
add_data_proc(client,token,url_base,'t0925','日光',61923,'1954-1-11')
console.error ("*** 終了 ***")
// ---------------------------------------------------------------
get_token.js
// ---------------------------------------------------------------
// get_token.js
//
// Feb/01/2020
//
// ---------------------------------------------------------------
exports.get_token_proc = function()
{
const execSync = require('child_process').execSync
const command = 'gcloud auth application-default print-access-token'
const result = execSync(command).toString().trim()
return result
}
// ---------------------------------------------------------------
実行コマンド
export NODE_PATH=/usr/lib/node_modules
export GOOGLE_APPLICATION_CREDENTIALS="***.json"
./firestore_create_rest.js