getting api keys from module.exports - node.js

I have two files a config.js and main.js I am storing api keys in my config.js
like this
function getGoogleApiKey(){
return 'KeyGoogle';
}
function getApiKey(){
return 'keyApi'
}
function getApiKey2(){
return 'keyApi2'
}
module.exports = {
getGoogleApiKey,
getApiKey,
getApiKey2,
}
I would like to get specific keys from the config.js file when I need it. I want to use some keys on my main.js
Here is my main.js.
const {config} = require('./config.js');
const googlePlaces = new GooglePlaces(config.getGoogleApiKey, 'json');
const awesome = new awesome(config.getApiKey);
I am note sure how to get the keys, I also tried it in this way but I get errors.
const {getGoogleApiKey, getApiKey, getApiKey2} = require('./config.js');
const googlePlaces = new GooglePlaces(getGoogleApiKey, 'json');

This line:
const {config} = require('./config.js');
is pulling out a config property from the value returned by require('./config.js'), which is non-existent in config.js.
Instead, just use this:
const config = require('./config.js');
which will assign the exported value (the module.exports object), and will work as expected.
Secondly, functions are being exported and not primitive (string) properties, so one or the other will need to be changed: export string properties directly or convert main.js to use the appropriate function call notation.
For example:
const googlePlaces = new GooglePlaces(config.getGoogleApiKey(), 'json');
const awesome = new awesome(config.getApiKey());

Related

Shopify API Node/Express Cannot read properties of undefined (reading 'Rest')

Just starting off with Shopify, and trying to get an order. Following the Shopify API documentation, here is my code:
const Shopify = require('#shopify/shopify-api');
const client = new Shopify.Clients.Rest('my-store.myshopify.com',
process.env.SHOPIFY_KEY);
module.exports.getShopifyOrderById = async (orderId) => {
return await client.get({
path: `orders/${orderId}`,
});
}
I get the following error when I execute this code:
TypeError: Cannot read properties of undefined (reading 'Rest')
Can't seem to figure out what the issue is.
You need to use Object destructing to get the Shopify object or use default export like below.
const { Shopify } = require('#shopify/shopify-api');
const client = new Shopify.Clients.Rest('my-store.myshopify.com',
process.env.SHOPIFY_KEY);
OR
const Shopify = require('#shopify/shopify-api').default;
const client = new Shopify.Clients.Rest('my-store.myshopify.com',
process.env.SHOPIFY_KEY);
OR
const ShopifyLib = require('#shopify/shopify-api');
const client = new ShopifyLib.Shopify.Clients.Rest('my-store.myshopify.com',
process.env.SHOPIFY_KEY);
This has to do with how ES6 modules are emulated in CommonJS and how you import the module. You can read about that here.

How to use module in my own node js module?

How I can use third party module in my own? For example if I have in app main file something like (using body-parser):
app.post("/dothis", (req,res)=>{
var name = req.body.name;
console.log(name);
};
This work fine. But when I want to have this in separate file (for example mod.js), and wrote like this:
exports.own = function(){
var name = req.body.name;
console.log(name);
}
Then in main file wrote:
const mod = require(__dirname + "/mod.js")
app.post("/dothis", (req,res)=>{
mod.own();
};
Then I get error like, req is undefined.
I am trying to add in mod.js file
const {req} = require ("http");
So then I got error that can't read value of name undefined.
There is the question, how i can transfer my code which is using body-parser, express and other modules to separate file or creating own module to get working module?
Thanks!
You are getting undefined because you are not passing the request.
Looking at your code, try this.
exports.own = function(req){ // use request
var name = req.body.name;
console.log(name);
}
const mod = require(__dirname + "/mod.js")
app.post("/dothis", (req,res)=>{
mod.own(req); // pass request
};

Algolia Nodejs Firebase syncing - .on('child_added') won't get called

I have a NodeJS script in which I'm watching trees in my Firebase database to see if an entry has been added/changed/removed via the child_added, childed_changed, and child_removed properties of the Firebase Admin .on() function in order to sync entries with my Algolia database.
The problem is that when I add/change/remove an item on these trees, the functions themselves never get fired.
However, when I start the script, I also have a .once('value', initialImport) function I call that works fine.
So for example, here is my relevant child_added code in my NodeJS script:
var dotenv = require('dotenv');
var firebaseAdmin = require("firebase-admin");
var algoliasearch = require('algoliasearch');
// load values from the .env file in this directory into process.env
dotenv.load();
var serviceAccount = require("./serviceAccountKey.json");
firebaseAdmin.initializeApp({
credential: firebaseAdmin.credential.cert(serviceAccount),
databaseURL: process.env.FIREBASE_DATABASE_URL
});
var database = firebaseAdmin.database();
var algolia = algoliasearch(process.env.ALGOLIA_APP_ID, process.env.ALGOLIA_API_KEY);
var users = algolia.initIndex('users');
var bandsRef = database.ref("/social/bands");
bandsRef.on('child_added', addOrUpdateBandIndexRecord);
/**
* Add or update a band index record
*/
function addOrUpdateBandIndexRecord(dataSnapshot) {
// Get Firebase object
var firebaseObject = dataSnapshot.val();
// Specify Algolia's objectID using the Firebase object key
firebaseObject.objectID = dataSnapshot.key;
// Add or update object
bands.saveObject(firebaseObject, function(err, content) {
if (err) {
throw err;
}
console.log('Firebase<>Algolia band object saved', firebaseObject.objectID);
});
}
This never runs :/ Is there something I'm doing wrong? This used to work once upon a time.
UPDATE: The issue I was having was that I was also calling a .once() on the ref that I was adding the .on('child_added') and this was causing a conflict. Once I removed the code for .once(), it solved the syncing issue. In order to do an initial import, you'll most likely want that code in a separate node file. This is what worked for me, anyway.

NodeJS (Express) - project structure and mongo connection

I started a new project from scratch with ExpressJS.
Everything works fine but now I begin to have a dozen of 'app.get(....)' function and I need to give the project a structure.
What I have in mind is quite simple, it should have a folder named 'routes' containing a file such as 'module1.js', with all of the app.get related to that module. (like I've seen in many examples)
The issue is how to tell Express to route 'http://url/module1/' to that route file and how to pass it a param variable, containing for instance the mongodb connection.
what I tried is :
var params = {
db: myMongoConnection
};
var mod1 = require('routes/module1');
app.use('/module1', mod1);
but now I still miss the 'params'.
If I try to pass it as an argument to the require method i get an error saying it needs middleware.
Another issue is related to the fact that the myMongoConnection is valid in the connection callback, so I think i need to require and use the route.js inside the MongoClient connect callback.
Any idea?
thanks a lot
For custom modules, create a folder, call it modules
In its index.js, expose the modules that you need.
Something like,
var mods = [
'mod1',
'mod2',
];
function init() {
var expose = {};
var params = {
db: myMongoConnection
};
mods.forEach(mods, function (mod) {
expose[mod] = require('./' + mod)(params);
});
return expose;
}
// export init
module.exports = init;
In mod1.js, wrap the params
module.exports = function(params) {
// all your functions here will have access to params.
}
Then in, server/app.js, require this and set it in the app.
app.set('mods', require('path-to/modules'));
Now, you can access all your modules, using app.get('mods').moduleName.methodname

How can I pass a variable while using `require` in node.js?

In my app.js I have below 3 lines.
var database = require('./database.js');
var client = database.client
var user = require('./user.js');
user.js file looks just like ordinary helper methods. But, it needs interact with database.
user.js
exports.find = function(id){
//client.query.....
}
Apparently, I want to use client inside of the user.js file. Is there anyway that I can pass this client to the user.js file, while I am using require method?
I think what you want to do is:
var user = require('./user')(client)
This enables you to have client as a parameter in each function in your module
or as module scope variable like this:
module.exports = function(client){
...
}
This question is similar to: Inheriting through Module.exports in node
Specifically answering your question:
module.client = require('./database.js').client;
var user = require('./user.js');
In user.js:
exports.find = function(id){
// you can do:
// module.parent.client.query.....
}
You should just put the same code in user.js
app.js
var client = require('./database.js').client; // if you need client here at all
var user = require('./user.js');
user.js
var client= require('./database.js').client;
exports.find = function(id){
//client.query.....
}
I don't see any drawbacks by doing it like this...
Why do you use require, for scr, no prom use source. It's the same as require and we can pass args in this fuction.
var x="hello i am you";
console.log(require(x)); //error
console.log(source(x)); //it will run without error

Resources