Gathering detailed insights and metrics for fire-store-api
Gathering detailed insights and metrics for fire-store-api
Gathering detailed insights and metrics for fire-store-api
Gathering detailed insights and metrics for fire-store-api
npm install fire-store-api
Typescript
Module System
Node Version
NPM Version
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
3
fire-store-api is a simple nodejs db package API for accessing records in google firestore data base. It basically a very thin shell over the existing @google-cloud/firestore. It exposes simple CRUD operations for document create, read, update and delete.
1npm i fire-store-api
You have a Fire Store Database instance up and running You have your google credentials on hand.
This can be quite a tricky part. However I will try to break it down for you.
There are three ways to access google cloud resources
If: Your application is running on google cloud then the best way to access your Fire Store database is via a service account. You may create a service account via gcloud tool or a REST url and running the following commands.
Ref:
https://cloud.google.com/iam/docs/creating-managing-service-accounts
https://github.com/googleapis/google-api-nodejs-client
Have following information:
service account email id: <SA_NAME>@<PROJECT_ID>.iam.gserviceaccount.com
You also provide the following information when you create a service account:
- SA_DESCRIPTION is an optional description for the service account.
- SA_DISPLAY_NAME is a friendly name for the service account.
- PROJECT_ID is the ID of your Google Cloud project.
A REST command
POST https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts
Request JSON body:
{
"accountId": "SA_NAME",
"serviceAccount": {
"description": "SA_DESCRIPTION",
"displayName": "SA_DISPLAY_NAME"
}
}
There multiple other ways that one may explore on google link provided above. The simplest option is to go your project dashboard follow the instructions and have a service account created. After creation of your project service account get it as a json file. This file needs to stored in env variable GOOGLE_APPLICATION_CREDENTIALS=/path/to/SA_key.json. For nodejs projects the best option is to use dotenv package and store it .env file.
Pass this as an env var to docker run command if being used for a docker image.
This is the simplest and the safest way. For applications running on non google resources you may want to explore google's OAuth flows.
And that is how database constructor below knows to connect to your database without any credentials
If: You have need using your access tokens for posting rest urls, then the following will help you get there.
command line tool:
1 gcloud auth application-default print-access-token 2
or
NodeJs function:
1 2 const { JWT } = require('google-auth-library'); 3 4 async function getToken(keys, url, scopes) { 5 // keys : service_account.json 6 // scopes: ['https://www.googleapis.com/auth/cloud-platform'], 7 // const url = `https://dns.googleapis.com/dns/v1/projects/${keys.project_id}`; 8 9 const client = new JWT({ 10 email: keys.client_email, 11 key: keys.private_key, 12 scopes: scopes, 13 }); 14 15 const result = await client.request({ url }); 16 17 //req.session.jwt = client; 18 //req.session.access_token = client.credentials.access_token; 19 // console.log(req.session.jwt.credentials.access_token); 20 return client; 21 22 } 23
Initialize the api constructor.
1var Database = require('fire-store-api'); 2 3const db = new Database({ 4 project_id, 5 cache_max_age, 6 cache_allocated_memory, 7})
Property | Type | Description | Default value |
---|---|---|---|
project_id | String | Google Cloud Platform project ID | |
cache_max_age | Number (seconds) | Cached data age threshold | 3600 |
cache_allocated_memory | Number (MB) | Maximum in-memory cache size, in megabytes | 64 |
When retrieving data, if the cache-matched data was added more than cache_max_age
seconds ago, we do not return the cached data
Following is a sample code used in express js. The fire-store-api is used by controllers which are linked to routes via a standard route file.
####################################################################################
Following is a sample code from controllers in express js. These controllers
are the functions tied to the routes in
####################################################################################
1var Database = require('fire-store-api'); 2 3const db = new Database(); 4 5
1 2const basicContrl = (req, res, next) => { 3 console.log("Url: ", req.url); 4 //res.locals.data = { "hello": "world !!!" }; 5 //next(); 6 res.json({ "hello": "world !!!" }); 7 8} 9
1 2const readOneCtrl = (req, res, next) => { 3 if (req.params.id) { 4 db.readOne(req.params) 5 .then((doc) => { 6 if (doc.exists) { 7 //res.locals.data = doc.data(); 8 //next(); 9 res.json(doc.data()); 10 } else { 11 12 console.log("No such document!"); 13 res.json({ "error": "Document does not exist" }); 14 } 15 }) 16 .catch((error) => { 17 // The document probably doesn't exist. 18 console.log("Error getting document:", error); 19 res.json({ "error": error }); 20 }); 21 22 } else { 23 console.log("Get Doc failed. Improper Id"); 24 res.json({ "error": "Get Doc failed. Improper Id" }); 25 } 26 //next(); 27 28}
1 2const readManyCtrl = (req, res, next) => { 3 if (req.params.collection) { 4 let arr = []; 5 const lim = req.query.limit ? req.query.limit : 10; 6 console.log("limit: ", lim); 7 db.readMany(req.params, lim) 8 .then((snapshots) => { 9 snapshots.forEach((doc) => { 10 arr.push(doc.data()); 11 }) 12 }) 13 .then(() => { 14 //res.locals.data = arr; 15 //next(); 16 res.json(arr); 17 }) 18 .catch(err => { 19 console.log(err); 20 res.json(err); 21 }) 22 23 } else { 24 console.log("Get collections failed"); 25 res.json({ "error": "Get Doc collections failed. Improper Id" }); 26 } 27 //next(); 28 29} 30
1 2const writeCtrl = (req, res, next) => { 3 const params = {} 4 params['collection'] = req.params.collection; 5 6 db.write(params, req.body); 7 8 res.json(req.body); 9 //next(); 10}
1 2 3const updateDocCtrl = (req, res, next) => { 4 5 if (req.params.id) { 6 const params = {} 7 params['collection'] = req.params.collection; 8 params['id'] = req.params.id; 9 //console.log("Controller params id",params['id']); 10 db.write(req.params, req.body); 11 } else { 12 console.log("Doc update failed. Improper Id"); 13 } 14 res.json(req.body); 15 //next(); 16}
1 2const deleteDocCtrl= (req, res, next) => { 3 4 if (req.params.id) { 5 const params = {} 6 params['collection'] = req.params.collection; 7 params['id'] = req.params.id; 8 db.deleteDoc(req.params); 9 } else { 10 console.log("Doc delete failed."); 11 } 12 res.json(req.body); 13 //next(); 14}
1 2module.exports = { 3 writeCtrl, 4 readOneCtrl, 5 updateDocCtrl, 6 readManyCtrl, 7 deleteDocCtrl 8 9}
####################################################################################
1var express = require('express'); 2var controllers = require('../controllers'); 3var router = express.Router();
1 2router 3 .route('/') 4 .get(controllers.basicContrl);
1 2 router 3 .route('/:collection/:id') 4 .get(controllers.readOneCtrl) 5 .post(controllers.updateDocCtrl) 6 .delete(controllers.deleteDocCtrl)
1 2router 3 .route('/:collection') 4 .get(controllers.readManyCtrl) 5 .post(controllers.writeCtrl)
1 2module.exports = router; 3
####################################################################################
https://www.npmjs.com/package/@google-cloud/firestore
https://github.com/sanchil/fireStoreAPI
https://www.npmjs.com/package/fire-store-api
https://cloud.google.com/iam/docs/creating-managing-service-accounts
https://github.com/googleapis/google-api-nodejs-client
We use SemVer for versioning. For the versions available, see the tags on this repository.
No vulnerabilities found.
No security vulnerabilities found.