firebase functions with top level variables state - firebase

I have firebase functions defined in index.ts file. This is importing another .ts file as below
import * as CommonCode from './common-code'
The common-code.ts have few variables declared at the top like below
export let baseUrl = ''
There are two functions inside index.ts as follows:
exports.function1 = functions.https.onRequest(async (req:any, res:any) => {
CommonCode.baseUrl = 'MyXXX.mydomain.com'
})
exports.function2 = functions.https.onRequest(async (req:any, res:any) => {
var x = CommonCode.baseUrl
})
if i make a call to function1 which is setting value of baseUrl. And then make call to function2 then will function2 persist the value set as a result of function1 or will be blank?
my understanding is that it should become blank when i call function2 every time as i am not setting it anywhere in function2. But with some observed weird behavior looks like my understanding is not correct. So what is the expepected behavior here?

Related

In redux, why are action types defined first as a constant rather than being named directly in the function?

I'm new to front-end development, so maybe someone could kindly clarify the following:
In Redux, I see in all the video tutorials that actions are defined like so:
const SOME_ACTION = "SOME_ACTION"
export const someAction = () => ({
type: SOME_ACTION
})
I wonder, what's the point of defining the SOME_ACTION constant?
Why not just skip it and name the action in the function itself? For instance:
export const someAction = () => ({
type: "SOME_ACTION"
})
What are we gaining by having a global variable that is only used within a function by the same name?
Many thanks!

How to call endpoint.select() in RTK query with an argument to retrieve cached data (within another selector)?

I have an endpoint which accepts a parameter and I'm trying to access the cached data using endpoint.select() in a redux slice. The problem is i cant figure out how to pass in the cache key. I've done the following:
export const selectProductsResult = (storeId) =>
storeApi.endpoints.listProductsByStore.select(storeId);
This works fine if I use it within a component like this:
const currentStoreProducts = useSelector(selectProductResult(currentStoreId))
What I don't understand is how I can use this in another selector, for example this does not work:
const selectCurrentProducts = createSelector((selectCurrentStoreId), currentStoreId
=> selectProductResult(currentStoreId)
If I try to use this in a component like so:
const currentProducts = useSelector(selectCurrentProducts)
The value obtained is a memoized function. I've played around quite a bit and can't seem to build the desired selector.
The call to someEndpoint.select() generates a new selector function that is specialized to look up the data for that cache key. Loosely put, imagine it looks like this:
const createEndpointSelector = (cacheKey) => {
return selectorForCacheKey = () => {
return state.api.queries['someEndpointName'][cacheKey];
}
}
const selectDataForPikachu = createEndpointSelector('pikachu');
So, you need to call someEndpoint.select() with the actual cache key itself, and it returns a new selector that knows how to retrieve the data for that cache key:
const selectDataForPikachu = apiSlice.endpoints.getPokemon.select('pikachu');
// later, in a component
const pikachuData = useSelector(selectDataForPikachu);

I can't seem replicate my data in firestore to algolia

Basically, I'm trying to replicate my data that's already in firebase into algolia through firebase cloud functions. The code doesn't compile and I can't seem to figure out why.
I'm using typescript, not javascript and am following this article right here.
https://medium.com/#soares.rfarias/how-to-set-up-firestore-and-algolia-319fcf2c0d37
I'm also working in VScode
// This is at the top of my file
const algoliasearch = require('algoliasearch')
const algoliaClient =
algoliasearch(functions.config().algolia.appid,
functions.config().algolia.apikey)
export const sendCollectionToAlgolia =
functions.https.onRequest(async (req, res) =>
{
const collectionIndex = algoliaClient.initIndex('Organizations')
const db = admin.firestore()
const algoliaRecords = []
const querySnapshot = await db.collection("Organizations").get()
querySnapshot.docs.forEach(doc => {
const document = doc.data()
const record = {
objectID: doc.id,
"orgUsername": document.orgUsername,
"orgName": document.orgName,
"school": document.school
}
algoliaRecords.push(record)
})
collectionIndex.saveObjects(algoliaRecords, (_error: any, content:
any) => {
res.status(200).send("COLLECTION was indexed to Algolia
successfully.");
})
})
I keep getting the compile error that says "Variable 'algoliaRecords' implicitly has type 'any[]' in some locations where its type cannot be determined" and I do not know how to fix it. I'm relatively new to algolia but have been doing cloud functions for a little bit.
This happens because algoriaRecords does not have an explicit type. Typically, TypeScript will infer types based on what you end up assigning later on. However, each subsequent algoriaRecords.push() operation evolves the type of the variable in accordance with the elements added to it.
A quick fix to this is by explicitly giving a type to algoriaRecords like such:
const algoriaRecords:Object[] = []
Furthermore, you can make TypeScript tolerate params with no types declared, see here for more information by configuring your tsconfig.js file and settting the noImplicitAny to false while removing the strict rule
// "strict": true
"noImplicitAny" : false

Firebase cloud function server side global variables

It's possible to have a sort of a global variable on firebase cloud functions?
I mean I could have an index.js like that in which set-up a global variable, let's say panicModeVariable.
And I would like to check in my cloud functions this variable before doing anything, like here in the auth create user trigger.
const functions = require('firebase-functions');
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);
var globalVariable = false;
// Create Account User
exports.createUserAccount = functions.auth.user().onCreate(event => {
if (!globalVariable) {
const uid = event.data.uid
const email = event.data.email
const photoUrl = event.data.photoURL
}
[...]
I tried with two dummy functions
exports.setGlobal = functions.https.onRequest((request, response) => {
globalVariable = true;
response.send("Set " + globalVariable);
});
exports.getGlobal = functions.https.onRequest((request, response) => {
response.send("Read " + globalVariable);
});
But it seems that I cannot access this variable in the way I intended.
The writing function it uses a 'local' variable, while the reading one uses the initial value, always.
I'd like to do that, if it is possible, to have a sort of server side variable to be read directly without the need to a call to the SDK to read, let's say, a database stored value (so that to not have a function call counting).
You could use Environment Config variables https://firebase.google.com/docs/functions/config-env
As far as I'm aware, you can't set them in the function themselves, they need to be set by CLI before you upload a function.
You could do something like firebase functions:config:set panic.mode=true
Then in your createUserAccount function you could call functions.config().panic.mode
But this won't help you set the variable via the https trigger. For that you'll need to make use of the database.

Passing in redux-devtools to a redux store with middleware

How is this code processed in relation to the way it is written in the redux-devtools documentation?
https://github.com/auth0-blog/redux-auth/blob/master/index.js#L10-L12
let createStoreWithMiddleware = applyMiddleware(thunkMiddleware, api)(createStore)
let store = createStoreWithMiddleware(quotesApp)
I'm not sure how to rewrite this to include DevTools but I did find this GitHub link including a pull request to include DevTools, which I've since gotten working. However, I still do not understand how it is being applied and what's going on with the let something = function(param1,param2)(function). I know that with that syntax the return value of applyMiddleware is being sent to createStore, but the createStore syntax takes a reducer, initialState, and an enhancer. How is this being applied here?
import { createDevTools } from 'redux-devtools'
import LogMonitor from 'redux-devtools-log-monitor'
import DockMonitor from 'redux-devtools-dock-monitor'
const DevTools = createDevTools(
<DockMonitor toggleVisibilityKey="ctrl-h" changePositionKey="ctrl-q">
<LogMonitor theme="tomorrow" preserveScrollTop={false} />
</DockMonitor>
)
let createStoreWithMiddleware = applyMiddleware(thunkMiddleware, api)(createStore)
let store = createStoreWithMiddleware(quotesApp, DevTools.instrument())
The syntax confuses me as opposed to the following syntax from the redux-devtools documentation.
What happens to initialState? In the example there is no reference to initialState anywhere.
The store enhancer definition signature looks roughly like this (snipped from the definition of `applyMiddleware):
export default function applyMiddleware(...middlewares) {
return (createStore) => (reducer, preloadedState, enhancer) => {
// snip actual enhancer logic
return {
...store,
dispatch
}
}
}
So, the enhancer definition actually returns a function that takes a reference to the createStore function itself.
Unfortunately, somehow people seem to have copied that very functional-oriented calling pattern from somewhere, which is really hard to understand. Not sure if it was in an earlier version of the docs, or what. Note that that particular usage pattern doesn't allow defining initialState (or, as it's about to be renamed, preloadedState).
So yes, the current definition pattern, and the one that I think is much more readable, is:
const middlewares = [thunk, myMiddleware];
const middlewareEnhancer = applyMiddleware(...middlewares);
const enhancers = compose(middlewareEnhancer, someOtherEnhancer);
const store = createStore(reducer, preloadedState, enhancers);

Resources