Cannot read property 'getInstanceByContextId' of undefined - nestjs

app.resolve(token) throws UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'getInstanceByContextId' of undefined
Current behavior
bootstrap function cannot resolve this transient provider:
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// fails on versions below 8.0.0 !!!
const logger = await app.resolve<AbstractLoggerService>(LOGGER_TOKEN);
logger.setContext('bootstrap');
app.useLogger(logger);
await app.listen(3000);
}
Expected behavior
NestJS should resolve Logger provider and launch application without any errors.

Solution:
Upgrade nestjs/common and nestjs/core to 8.0.0 or above

Related

Firestore serverTimestamp() undefined

Problem
I have a callable cloud function set up which writes to Firestore using the Admin SDK (node.js):
const admin = require('firebase-admin');
const functions = require("firebase-functions");
exports.myFunction = functions.https.onCall(async (data, context) => {
await admin.firestore().doc("/test").create({
timestamp: admin.firestore.FieldValue.serverTimestamp()
});
})
Testing this using the emulators. Also my packages are:
"firebase-admin": "^11.2.1",
"firebase-functions": "^4.0.2",
"firebase-tools": "11.16.0"
I am getting this error in my emulator logs:
TypeError: Cannot read properties of undefined (reading 'serverTimestamp')
I recently updated the admin SDK and the firebase-tools to the versions above, then the problem started occurring. I tried reinstalling firebase-tools and the admin SDK without luck.
Anyone have an idea of what I could try?
Found the API reference here. Instead of timestamp: admin.firestore.FieldValue.serverTimestamp() it should be timestamp: Firestore.FieldValue.serverTimestamp()
Also import: const { Firestore } = require("firebase-admin/firestore");

Nest.js Testing Error: Using the "extends Logger" instruction is not allowed in Nest v8. Please, use "extends ConsoleLogger" instead

Here's the problem I have:
I am using my custom Logger in Nest.js:
export class ReportLogger extends ConsoleLogger {
verbose(message: string) {
console.log('【Verbose】Reporting', message);
super.verbose.apply(this, arguments);
}
log(message: string) {
console.log('【Log】Reporting', message);
super.log.apply(this, arguments);
}
}
And the log.interceptor.ts file:
export class LogInterceptor implements NestInterceptor {
constructor(private reportLogger: ReportLogger) {
this.reportLogger.setContext('LogInterceptor');
}
intercept(context: ExecutionContext, next: CallHandler) {
const http = context.switchToHttp();
const request = http.getRequest();
const now = Date.now();
return next
.handle()
.pipe(
tap(() =>
this.reportLogger.log(
`${request.method} ${request.url} ${Date.now() - now}ms`,
),
),
);
}
}
And here's the main.ts file:
async function bootstrap() {
const reportLogger = new ReportLogger();
const app = await NestFactory.create<NestExpressApplication>(AppModule, {
cors: {
origin: ['http://localhost', 'http://localhost:3000'],
credentials: true,
},
bufferLogs: true,
logger: reportLogger,
});
app.useGlobalInterceptors(
new LogInterceptor(reportLogger),
);
setupSwagger(app);
await app.listen(4200);
}
When I run npm run start:dev to run the Nest App on dev, everything works fine. But when I run npm run test:e2e or npm run test on testing, it shows this error:
Using the "extends Logger" instruction is not allowed in Nest v8. Please, use "extends ConsoleLogger" instead.
10 | const moduleFixture: TestingModule = await Test.createTestingModule({
11 | imports: [AppModule],
> 12 | }).compile();
| ^
13 |
14 | app = moduleFixture.createNestApplication();
15 | await app.init();
I read the Nest.js doc again, and found the Logging breaking change in the docs. But the question is I have already made my ReportLogger extends ConsoleLogger, why this error shows again? And why it only shows in testing?
I have faced the same problem after upgrading NestJS to version 8.
Later on, I found that package #nestjs/testing had previous version installed and was not upgraded to the latest version. The reason is, previous version of NestJS testing module is using the old Logger.
In order to fix this issue, you just need to upgrade the NestJS testing module.
Run this command for Latest version:
npm i #nestjs/testing#latest
OR specific version
npm i #nestjs/testing#8.0.6 // <--- Change the NestJS version here
After this, just build and run test cases again.
External Links:
NestJS Testing NPM
even with "#nestjs/testing": "^8.0.7" this issue still occurs
class Logger implements LoggerService { ... }
await Test.createTestingModule({
imports: [ApiModule],
})
.setLogger(new Logger())
.compile();
setting logger instance solves that error on my side

Error while executing node (about firebase), but app works fine, even using firebase (angular-universal)

I am using angular-universal to connect angular and node.js, while using firebase as dummy-data.
The app works using both angular and node (even fetching and saving data in firebase).
While running in angular, there are no errors in the console (both the browser console and ng serve).
While running in node it logs an error in the console, about firebase (even though the app works using firebase).
This is the error:
ERROR TypeError: firebase.initializeApp is not a function
at AppComponent../src/app/app.component.ts.AppComponent.ngOnInit (C:\Users\****\Desktop\****\Fevereiro\projeto\dist\server.js:131902:18)
at checkAndUpdateDirectiveInline (C:\Users\*****\Desktop\*****\Fevereiro\projeto\dist\server.js:27407:19)
at checkAndUpdateNodeInline (C:\Users\*****\Desktop\*****\Fevereiro\projeto\dist\server.js:28671:20)
at checkAndUpdateNode (C:\Users\*****\Desktop\*****\Fevereiro\projeto\dist\server.js:28633:16)
at prodCheckAndUpdateNode (C:\Users\*****\Desktop\*****\Fevereiro\projeto\dist\server.js:29174:5)
at Object.updateDirectives (C:\Users\*****\Desktop\*****\Fevereiro\projeto\dist\server.js:131877:264)
at Object.updateDirectives (C:\Users\*****\Desktop\*****\Fevereiro\projeto\dist\server.js:28962:72)
at Object.checkAndUpdateView (C:\Users\*****\Desktop\*****\Fevereiro\projeto\dist\server.js:28615:14)
at ViewRef_.detectChanges (C:\Users\*****\Desktop\*****\Fevereiro\projeto\dist\server.js:26996:22)
at C:\Users\*****\Desktop\*****\Fevereiro\projeto\dist\server.js:23427:63
Code of (C:\Users****\Desktop****\Fevereiro\projeto\dist\server.js) that calls the method initializeApp:
Object.defineProperty(exports, "__esModule", { value: true });
var core_1 = __webpack_require__(/*! #angular/core */ "#angular/core");
var firebase = __webpack_require__(/*! firebase */ "firebase");
var AppComponent = /** #class */ (function () {
function AppComponent() {
this.loadedFeature = 'recipe';
}
AppComponent.prototype.ngOnInit = function () {
firebase.initializeApp({
apiKey: "******",
authDomain: "******",
});
};
AppComponent.prototype.onNavigate = function (feature) {
this.loadedFeature = feature;
};
return AppComponent;
}());
exports.AppComponent = AppComponent;
I had the same problem before when I imported from 'firebase'. You should import firebase from 'firebase/app'

Node.js - FireBas - Functions, TypeError: Cannot read property 'user_id' of undefined [duplicate]

I am trying to do a simple hello world firebase function with my mobile app, I want to log the user ID so I can see that the function does work.
This is my current javascript code:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('/notifications/{user_id}').onWrite((event) => {
console.log('Testing stuff', event.params.user_id);
return;
});
It does trigger when new data is written to specific databasetable but this error shows up:
TypeError: Cannot read property 'user_id' of undefined
at exports.sendNotification.functions.database.ref.onWrite (/user_code/index.js:8:44)
at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27)
at next (native)
at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:82:36)
at /var/tmp/worker/worker.js:700:26
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
The notification database looks like this:
You need to install the latest firebase-functions and firebase-admin:
npm install firebase-functions#latest firebase-admin#latest --save
npm install -g firebase-tools
to be able to use the new API, check here for more info:
https://firebase.google.com/docs/functions/get-started#set_up_and_initialize
Change this:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('/notifications/{user_id}').onWrite((event) => {
console.log('Testing stuff', event.params.user_id);
into this:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.sendNotification = functions.database.ref('/notifications/{user_id}').onWrite((change, context) => {
console.log('Testing stuff', context.params.user_id);
For onWrite and onUpdate events, the data parameter has before and after fields. Each of these is a DataSnapshot with the same methods available in admin.database.DataSnapshot
params
An object containing the values of the wildcards in the path parameter provided to the ref() method for a Realtime Database trigger.
more info here:
Cloud functions v1.0 Changes
EventContext#params
Change

web3, truffle, nodejs error : UnhandledPromiseRejectionWarning

var web3 = require('web3'),
contract = require('truffle-contract'),
path = require('path'),
MyContractJSON = require(path.join(__dirname, '../tru_dir/build/contracts/NewCoin.json'));
var provider = new web3.providers.HttpProvider("http://localhost:8545");
var MyContract = contract(MyContractJSON);
MyContract.setProvider(provider);
MyContract.deployed().then(function(instance){
return instance.returnfive();
})
.then(function(result) {
console.log(result);
}, function(error) {
console.log(error);
});
I set this code to call a smart contract function that returns 5.
I tested it with truffle console and it works properly.
But when trying to get the same result using nodejs it crashes giving those 2 errors :
(node:6227) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: Cannot read property 'apply' of undefined
(node:6227) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Any idea about the issue ?
Replace MyContract definition with
const MyContract = artifacts.require("MyContractewCoin")
// You are missing this step before invoking deployer
await deployer.deploy(MyContract)
const dMyContract = await MyContract.deployed()
// now you can do stuff like
let result = await dMyContract.someContractFunction(args)

Resources