commenting async in globals.js doesn't affect its usage in services - node.js

Can someone give me some elementary tips about globals.js in sails.js, I have below questions.
I commented async in globals.js, I have removed async module which was installed in my project, now in a service I commented line //var async = require('async'); My code still works where ever I used async, I am new to sails and exploring the use of globals.js, is that like if async is commented any usage should throw an error "undefined".
How to add my own module to globals.js?
How is bootsrap.js different from global.js?
Appreciate your discussions and explanation.
Thanks

1) async is module that exposed to global by Sails. Here is the code that responsible for it (full code here - https://github.com/balderdashy/sails/blob/a210b48667708bea687dd5ec61ce9e07ffc0c005/lib/app/private/exposeGlobals.js#L35)
if (sails.config.globals.async !== false) {
global['async'] = async;
}
You need to set async to false in config/globals.js and then you can't call async.
2) It's not a frameworks' question. You just make global['myModule'] = myModule but don't do this, please.
3) bootstrap.js is a function that calls before sails initialisation.

Okay so async is by default commented in globals.js and is available globally. When I uncommented that and set "async: false" I got the error I expected.
error: Error (E_UNKNOWN) :: Encountered an unexpected error
ReferenceError: async is not defined

Related

Refactoring nestJS circular dependency on modules without using forwardRef

In this github issue author uses process nextTick to solve the issue. But it is not recommended.
You can fix this issue using the the process.nextTick() function:
async getUsers() {
await new Promise(resolve => process.nextTick(resolve)); // <- add this
console.log('getUsers function');
...
}
Still, using request-scoped providers in combination with circular dependencies is very unpredictable and I'd strongly recommend refactoring your code to get rid of them.
My Case is like the below:
AppLogModule imports AppDeployment -> AppLogService has multiple methods that use appdeploymentService.
Now AppDeploymentService wants to use appLogservice through importing the AppLogsModule. Only 1 method uses applogService in appDeploymentservice.

Firebase cloud functions master handling function

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.

How to auto-reload files in Node.js while using ESM?

I understand you can clear files from cache while using CommonJS simply by deleteing from require.cache and requireing the file again. However I've been unable to find an equivalent option when using ESM. Is this possible, and if so how?
Reading at esm issues it seems cache is intentionally not exposed.
I'm afraid the answer to your question is simply no.
it seems there is a solution using dynamic imports:
const modules = {
moduleA: async () => await import(`./module-a.js?v=${Date.now()}`)
}
Then use it like:
async function myTest() {
// module will be reset at each call of the function
const moduleA = await modules.moduleA()
}
Here is an issue about it with further details on that technique there

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.
});

Resources