Refactoring nestJS circular dependency on modules without using forwardRef - nestjs

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.

Related

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

Models with dependency injection in Nodejs

What is the best practice for injecting dependencies into models? And especially, what if their getter are asynchronous, as with mongodb.getCollection()?
The point is to inject dependencies once with
var model = require('./model')({dep1: foo, dep2: bar});
and call all member methods without having to pass them as arguments. Neither do I want to have each method to begin with a waterfall of async getters.
I ended up with a dedicated exports wrapper that proxies all calls and passes the async dependencies.
However, this creates a lot of overhead, it's repetitive a lot and I generally do not like it.
var Entity = require('./entity');
function findById(id, callback, collection) {
// ...
// callback(null, Entity(...));
};
module.exports = function(di) {
function getCollection(callback) {
di.database.collection('users', callback);
};
return {
findById: function(id, callback) {
getCollection(function(err, collection) {
findById(id, callback, collection);
});
},
// ... more methods, all expecting `collection`
};
};
What is the best practice for injecting dependencies, especially those with async getters?
If your need is to support unit testing, dependency injection in a dynamic language like javascript is probably more trouble than it's worth. Note that just about none of the modules you require from others are likely to use the patterns for DI you see in Java, .NET, and with other statically compiled languages.
If you want to mock out behavior in order to isolate specific units of code for testing, see the 'sinon' module http://sinonjs.org/. It allows you to dynamically swap in/out interceptors that can either spy on method calls or replace them altogether. In practice, you would write a mocha test where you require your module, then require a module that's leveraged in your code. Use sinon to spy or stub a method on that module and as a result, you can isolate your code.
There is one scenario where I've not been able to completely isolate 3rd party code with sinon, and this is when the act of require()ing a module executes some behavior that you don't want to run in your test. For that scenario, I made a super simple module called 'mockrequire' https://github.com/mateodelnorte/mockrequire that allows you to provide an inline mock to be required instead of the actual module. You can provide a mock that uses spy or stub from sinon and have the same syntax and patterns as all the rest of your tests.
Hopefully this answers the underlying question from your post. ;)
In very simple situations, you could simply export a function that modifies objects in your file scope and returns your actual exports object, but if you want to inject more variably (i.e. for more than one use from your app) it's generally better to create a wrapper object like you have done.
You can reduce some overhead and indentation in some situations by using a wrapper class instead of a function returning an object.
For instance
function findById(id, callback, collection) {
// ...
// callback(null, Entity(...));
};
function Wrapper(di) {
this.di = di;
}
module.exports = Wrapper; // or do 'new' usage in a function if preferred
Wrapper.prototype.findById = function (id, callback) {
// use this.di to call findById and getCollection
}, // etc
Other than that, it's not a whole lot you can do to improve things. I like this approach though. Keeps the state di explicit and separate from the function body of findById and by using a class you reduce the nesting of indentation a little bit at least.

Resources