Firebase cloud functions master handling function - node.js

In another stackoverflow post a master handling function that dispatches the processing to different functions was suggested.
functions.storage.object().onFinalize((object) => {
if (object.name.startsWith('User_Pictures/')) {
return handleUserPictures(object);
} else if (object.name.startsWith('MainCategoryPics/')) {
return handleMainCategoryPictures(object);
}
})
I have tried implementing this by having index.js as follows:
const handler = require('./handler');
exports.handler = handler.handler;
exports.userpictures = require('./userpictures');
exports.mainpictures = require('./mainpictures');
And in mainpictures.js having the following:
exports.handleMainCategoryPictures= async (object) => { ... code here ... }
When I ran firebase deploy no functions were detected. I was expecting 3. Is this type of structure possible, am I making some obvious mistake in terms of exporting correctly? When I tried exporting directly without the handler the functions were detected.

You still need to define your exported functions with the functions builder API. That's thing that goes like this in your first code bit:
export fun = functions.storage.object().onFinalize(...)
If you aren't using this API to build and export functions from index.js, then the Firebase CLI will find no function, and nothing will be deployed. You can use this API from a required file, if you want, but index.js must still ultimately export a function built like this.
If you are, in fact, using this and not showing it here, then I suggest you edit the question to show the complete, minimal example of all the files in play.

Related

Run code before NestJs Decorators initialization

Are there ways to get data and save from another microservice before decorator initialization? As I understand decorators initialize even before bootstrap function is called
Decorators evaluate to regular JS code that is evaluated when the file is required. The only way to run something before the decorator, is to have that something higher in the file, or before that file is even required in another script. It'd be like having
export const foo = () => {
console.log('foo');
}
console.log('Here we are exporting foo');
And wanting to run something before the console.log('Here we are exporting foo'). The only way is to have what you want to run higher up in the file, or before this file is every required

Why does my skill behave differently when I move the helper functions to a different module?

I'm trying to re-create the Alexa Quiz skill that's mentioned on their public repository. So far, the skill works correctly when the index.js file is exactly same as the one in the GitHub repo. I'm trying to move the constants in a separate data file and the helper functions in another file. When I move the constants in the separate file, the code works correctly. However, when I move the helper functions into a different file the code starts behaving differently.
I moved the constants to a different file called data.js and exported the variables in that file using
module.exports = {
skillBuilder,
imagePath,
backgroundImagePath,
correctAnswer,
wrongAnswer,
data,
states,
welcome,
startQuiz,
exitSkill,
reprompt,
help,
useCardsFlag
};
In index.js, I imported the variables using const Constants = require('data');
I tested the code after doing this and it works correctly (as it should).
Now, I moved the helper functions into a different file called functions.js and exported all the functions using
module.exports = {
getBadAnswer,
getCurrentScore,
getFinalScore,
getCardTitle,
getSmallImage,
getLargeImage,
getImage,
getBackgroundImage,
getSpeechDescription,
formatCasing,
getQuestion,
getQuestionWithoutOrdinal,
getAnswer,
getRandom,
askQuestion,
compareSlots,
getItem,
getSpeechCon,
getTextDescription
};
and imported the functions using const Helpers = require('functions');.
Because the functions also refer the constants, I also imported the constants in the functions.js using const Constants = require('data');
I expected the skill to work correctly. However, when I start the quiz using the skill, Alexa just utters the Help message.
Here is are my code files:
index.js
functions.js
data.js
I think what is happening is the variable states are not persisted between modules but I might be wrong. I have 2 questions:
Can anyone tell if my understanding of why this is happening is
correct?
How to prevent this?

typescript replaceent for require inside a function in nodejs

I trying to convert a nodejs project to TypeScript and while mostly I did not faced really difficult obstacles during this process, the codebase has few gotchas like this, mostly in startup code:
function prepareConfiguration() {
let cloudConfigLoader = require('../utils/cloud-config');
return cloudConfigLoader.ensureForFreshConfig().then(function() {
//do some stuff
});
}
I may be need just an advice on which approach for refactoring this has less code changes to be made to make it work in TypeScript fashion.
In response to comments, more details:
That require loads the node module, not a JSON file. From that module the ensureForFreshConfig function contacts with a cloud service to load a list of values to rebuild a configuration state object.
Problem is that mdule was made in standard node approach of "module is isngleton object" and its independencies include auth component that will be ready only when the shown require call is made. I know it is not best a way to do so..
Typesript does not allow "mport that module later" except with dynamyc import which is problematic as mentiond in comment.
The "good" approach is to refactor that part of startup and make the ensureForFreshConfig and its dependency to initiate its ntenras on demand via cnstructors.. I just hoped ofr some soluiton to reduce things to be remade durng this transition to the TypeScript
import { cloudConfigLoader } from '../utils/cloud-config'
async function prepareConfiguration() {
await cloudConfigLoader.ensureForFreshConfig()
// do some stuff
// return some-stuff
}
The function is to be used as follows.
await prepareConfiguration()

Proper use of artifacts.require?

I am trying to understand how artifacts.require should be used. I've seen the standard paragraph describing it as being for migrations and testing. From this I infer that the globally scoped artifacts with its method require are automatically defined by the truffle executable tool when doing migrations or running tests. However, I am working with some code that uses artifacts.require outside the context of any migrations or tests, rather, this code just needs to do the usual at and new. However, in this context, the object artifacts is not defined.
Do I have the right picture here? Is this an appropriate use of artifacts.require? If so, what must be done to make it be defined outside of migrations and testing?
Thanks for any suggestions!
artifacts.require really isn't meant to be used outside of a test. this is where it is defined: https://github.com/trufflesuite/truffle-core/blob/3e96337c32aaae6885105661fd1a6792ab4494bf/lib/test.js#L240
when in production code you should load the compiled contract into your application using truffle-contract https://github.com/trufflesuite/truffle-contract
here is a short example (from http://truffleframework.com/docs/getting_started/packages-npm#within-javascript-code and see
http://truffleframework.com/docs/getting_started/contracts#making-a-transaction )
var contract = require("truffle-contract");
var contractJson = require("example-truffle-library/build/contracts/SimpleNameRegistry.json");
var SimpleNameRegistry = contract(contractJson);
SimpleNameRegistry
.deployed()
.then(function(instance) {
return instance.setRegistry(address);
})
.then(function(result) {
// If this callback is called, the transaction was successfully processed.
alert("Transaction successful!")
})
.catch(function(e) {
// There was an error! Handle it.
});

Using node module in angularjs?

What's the best practice for using external code, e.g. code found in node modules, in angular?
I'd like to use this https://www.npmjs.com/package/positionsizingcalculator node module in my angular app. I've created an angular service intended to wrap the node module, and now I want to make the service use the node module.
'use strict';
angular.module('angularcalculator')
.service('MyService', function () {
this.calculate = function () {
return {
//I want to call the node module here, whats the best practice?
};
}
});
To do this, I would crack open the package and grab the .js out of it. This package is MIT license, so we can do whatever we want. If you navigate to /node_modules/positionsizingcalculator/ you'll find an index.js. Open that up and you'll see the moudle export, which takes a function that returns an object.
You'll notice this is an extremely similar pattern to .factory, which also takes a function that returns an object (or constuctor, depending on your pattern). So I'd do the following
.factory('positionsizingcalculator', function(){
basicValidate = function (argument) {
... //Insert whole declaration in here
return position;
})
and the inject it where you need it:
.controller('AppController', function(positionsizingcalculator){
//use it here as you would in node after you inject it via require.
})
--
Edit: This is good for one off grabs of the JS, but if you want a more extensible solution, http://browserify.org/ is a better bet. It allows you to transform your requirements into a single package. Note that this could result in pulling down a lot more code that you might otherwise need, if you make one require bundle for your whole site, as this is not true AMD, and you need to to load everything you might want one the client, unless you make page specific bundles.
You'd still want to do the require in a factory and return it, to keep it in angular's dependency injection framework.

Resources