I'm trying to set up a simple hybrid app using Nest's documentation, but the app gets stuck without throwing.
main.ts
import { NestFactory } from '#nestjs/core';
import { AppModule } from './app.module';
import { Logger } from '#nestjs/common';
import { ConfigService } from '#nestjs/config';
import { MicroserviceOptions, Transport } from '#nestjs/microservices';
const logger = new Logger('Main');
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const configService = app.get(ConfigService);
const redisConfig = configService.get('database.redis');
app.connectMicroservice<MicroserviceOptions>({
transport: Transport.REDIS,
options: {
url: `redis://${redisConfig.host}:${redisConfig.port}`,
},
});
await app.startAllMicroservices();
await app.listen(configService.get('app.port'));
}
bootstrap()
.then(() => logger.log('App running'))
.catch((e) => logger.error(e));
When I comment out app.startAllMicroservices() or the code connecting the microservice, the App running line is logged, with it, the app is stuck.
I am 100% certain Redis is up and running and responsive, I am using Bull which uses the same config and it runs just fine.
I have tried commenting out everything irrelevant to the above (everything besides the ConfigModule) in the app.module to no avail. Any help would be appreciated.
I am running the latest version of NestJS and its peer dependencies.
Just resolved a similar issue. As per the time of writing downgrade redis npm package to ^3 from anything high i.e ^4.
From nestjs microservice redis docs To start building Redis-based microservices, first install the required package (note as of now the supported Redis version is ^3, not the latest ^4):
Related
I'm trying to use the firebase admin SDK, heres my code:
import * as admin from 'firebase-admin';
var firebaseAdminAccount = require("../serviceAccount.json");
var app : admin.app.App = null;
if(!admin.apps.length)
{
app = admin.initializeApp({
credential: admin.credential.cert(firebaseAdminAccount)
})
}
if(app === null)
{
app = admin.apps[0];
}
export default app;
the idea behind this is that whenever used, it will check if the firebase admin SDK is initialized or not, if it's not, then it will initialize it, then export it.
My problem however is when I try to run this, it gives me the following error:
error -
./node_modules/firebase-admin/lib/app/firebase-namespace.js:106:0
Module not found: Package path ./standalone is not exported from
package D:\NewRepos\1d3a\node_modules#firebase\database-compat (see
exports field in
D:\NewRepos\1d3a\node_modules#firebase\database-compat\package.json)
Import trace for requested module:
./node_modules/firebase-admin/lib/default-namespace.js
./node_modules/firebase-admin/lib/index.js ./lib/firebaseAdminSdk.ts
./middleware.ts
https://nextjs.org/docs/messages/module-not-found\
I just installed everything so it should be on the latest version, anyone have an idea why this is happening?
Seems like I didn't realize that Next.js middleware runs on V8, and therefor, firebase-admin cannot run on it. Back to the drawing board.
I have tried to integrate firebase with Nuxt Js and i am getting this error
As per documentation first I have installed firebase with help of "npm install firebase" and then i have installed "npm install #nuxtjs/firebase" and third i have integrated my firebase config in modules in nuxt.config.js
so whats the solution to solve the above error?
Thanks in advance
It depends on which version of #nuxtjs/firebase you are using, because this package #nuxtjs/firebase is not compatible with firebase version 9+ supporting tree-shaking.
So you need to downgrade you package to firebase version 8 and prior.
For more information, please check the authors github issues.
If you are using the new Modular SDK v9.0.1 you might get the above error as it does not use firebase. namespace now,
Try using getApps() instead of firebase.apps.
import { initializeApp, getApps } from "firebase/app"
import { getFirestore } from "firebase/firestore"
import { getAuth } from "firebase/auth"
const firebaseConfig = {...}
if (!getApps().length) {
//....
}
const app = initializeApp(firebaseConfig)
const db = getFirestore(app)
const auth = getAuth(app) export {db, auth}
I banged my head against this problem for a while - I was trying to use the Realtime Database in a dynamic page and getting the same error. I finally went back to this issue on the firebase module repo. Basically I had to do two things:
use the async asyncData method instead of just defining data properties; and
use both the app and params variables.
So instead of this:
export default {
data: () => ({
items: []
)},
async fetch ({ params }) {
const ref = this.$fire.database.ref(`foo/${params.slug}`)
const data = (await ref.once('value')).val()
this.items = data
}
}
I had to do this:
export default {
async asyncData ({ app, params }) {
const ref = app.$fire.database.ref(`foo/${params.slug}`)
const data = (await ref.once('value')).val()
return { items: data }
}
}
I had a file with one function that creates an axiosInstance, it used to look like this:
import Axios from 'axios';
import getToken from '#/api/auth-token';
const [apiUrl] = [window.variables.apiUrl];
export const createApiInstance = () => {
return Axios.create({
baseURL: `${apiUrl}`,
headers: {
Authorization: `Bearer ${getToken()}`,
},
});
};
Something we wanted to implement was notifying the user when their JWT token expires (so they won't unwittingly continue using the app while all of their requests are returning 401s). My solution turned this file into this:
import Axios from 'axios';
import getToken from '#/api/auth-token';
import store from '#/main.jsx';
import { userActionCreators } from '#/store/action-creators';
const [apiUrl] = [window.variables.apiUrl];
export const createApiInstance = (urlExtension = '') => {
const axiosInstance = Axios.create({
baseURL: `${apiUrl + urlExtension}`,
headers: {
Authorization: `Bearer ${getToken()}`,
},
});
axiosInstance.interceptors.response.use(response => {
if (response.status === 401)
store.dispatch(userActionCreators.setUserTokenExpired());
return response;
});
return axiosInstance;
};
This worked very well, as now all of the responses from the API are being checked for a 401 Unauthorized status and dispatching an action so the app can respond to it.
Jest doesn't like the import store, so 95% of the tests in the app fail when the store is imported here. I'm certain it is the importing of the store because every test passes when it is commented it.
I've had absolutely no luck getting anything to work.
I've tried updating setting jest and babel-jest to the same versions, setting react, react-dom, and react-test-renderer to the same versions. I've looked into configuring moduleNameMapper to mock the store in the jest config in package.json but I'm not sure how to make that work. I'm starting to consider taking a completely different approach to this problem such as applying middleware to check for 401 responses instead, but I'm worried I'll end up running into the same issue after a bunch of work.
The problem with mocking the store in the test files themselves is that there's hundreds of test files in this large application, so literally anything besides adding mocking to each individual file is the solution I'm looking for.
If anyone else is having this problem, this occurred because I was exporting the store from the same file as my ReactDOM.render. Apparently you can export from this file but as soon as you try to import what is exported somewhere else it will catch it and break tests. The solution is to create and export the store from a different file.
Make sure you have a .babelrc file, as jest doesn't understand the context of babel and JSX files otherwise. Related Stack Qusetion
If that doesn't quite do the trick can you update with the main.jsx code and let me know then i'll update
I want to unit test a function in my application that calls and updates a Firebase reference. The problem I am facing is that when I try to run the test and import the file that contains the function, I get the following error SyntaxError: Unexpected token u in JSON at position 0 which points to the line in my function file that imports my reference to Firebase.
I am using Webpack and Babel on this project, so I tried setting a resolve.alias in the webpack.config file which worked when the application was running, but did not work when I ran npm test. At this point I'm at a loss as to how I can mock out the Firebase reference so I can test the other functions of the function. Here's some sample code:
constants/index.js
import firebase from 'firebase';
const firebaseConfig = JSON.parse(unescape(`${config.FIREBASE_CONFIG}`));
const mainApp = firebase.initializeApp(firebaseConfig);
export const ref = mainApp.database().ref();
actions/settings.js
import * as actions from './';
import { ref } from '../constants';
export const updateSetting = (e, value) =>
(dispatch) => {
ref.child('setting')
.set(value)
.then(() => {
dispatch(actions.confirmFBSave());
})
.catch((err) => {
dispatch(actions.failFBSave({ text: err.code }));
});
};
What testing framework are you using Qunit, jasmine, mocha? With AngularFire and Angular it is much easier because you can pass a mock class in at DI, but I have also tested non angular js for server side. Then I used Sinon to get mock initializeApp and return a Mock firebase app.
You could also try https://github.com/thlorenz/proxyquire I didn't need to go that far, but I have seen it suggested. That way you are essentially intercepting the import and swap it out for something you can test with.
Hopefully this is a simple question. I am trying to import MongoDB using the es6 import-from style. If I import using node require it works fine.
let mongo = require('mongodb');
let MongoClient = mongo.MongoClient;
But if I import it the es6 way it breaks without errors or logs.
import {MongoClient} from 'mongodb';
But it doesn't break when compiling/running it only breaks when I try to do anything with MongoClient.
Here is my Db Manager class-
import {MongoClient} from 'mongodb';
export class DbManager {
constructor() {
console.log('Constructing DB Connection');
}
}
When I run my server I get several logs from other managers and events.
mycomputer myuser$ ./start.sh
Server Constructing
Route Manager Constructing
Initializing Route: Static
Constructing DB Connection
http server started on port: 8000
But if I do a console.log of the MongoClient there is simply no output.
import {MongoClient} from 'mongodb';
export class DbManager {
constructor() {
console.log('Constructing DB Connection');
console.log(MongoClient);
}
}
And the output looks like this-
mycomputer myuser$ ./start.sh
mycomputer myuser$
There are no compile errors so I don't understand why this isn't working. Furthermore, I don't understand why there aren't any logs! This is one of the last things that happens, there should at least be logs up until that point I'd think. If you'd like to see my start.sh script here it is (quick and dirty, don't judge me):
tsc
echo "var System = require('systemjs');" > dist/final.js
babel dist/typescript.js >> dist/final.js
echo "System.import('main');" >> dist/final.js
node dist/final.js
EDIT
Continuing to search for the answer while waiting (hoping) for a response. I'm taking a look at the resulting final.js and if MongoClient is used anywhere in the file the System.register function call looks like this-
System.register("db/db.manager", ["mongodb"] ...
And if I don't use it (even if I import it) it does not show mongodb.
System.register("db/db.manager", [] ...
That would explain why nothing would happen. Something is wrong with trying to import mongodb. Not sure yet what to do.
EDIT EDIT
Found a solution. One i'm not thrilled with but maybe it's just the way it has to be.
I don't think I can rely on es6 imports. It looks like I can use it to import the typedefs but not the actual module. How I got around this is like this-
import {Db as MongoDb, MongoClient} from 'mongodb';
let mongodb = require('mongodb');
let mongoClient: MongoClient = mongodb.MongoClient;
A lot of extra work. If there's another way please let me know.
Listen, I know there are more than a handful of cracks at this solution here. Some may work for you, but for me, none solved me but the one below.
2021 UPDATE:
BORING BACKSTORY ALERT
We're using Node v14.16.0 and our package.json has "type": "module" set. So, our code is ES6+ and commonjs imports are a deal-breaker in most cases, especially when it comes to the MongoDB Native 3.6 NodeJS Driver.
Lucky for us, MongoDB Native ^4.0.0-beta.3 is written in TypeScript, and works as expected. Prepare your shattered sprits for liftoff. ;) Oh, and rather than store your secret sauce (user:pass and uri) in your source code, check out node-config and be safe.
THE SOLUTION
# This version will keep changing after this posts, so take heed.
$ cd path/to/your/project
$ npm i -s mongodb#4.0.0-beta.3
Inside your project:
import config from 'config'
// MongoDB
import { MongoClient } from 'mongodb'
const client = new MongoClient(config.get('mongodb.uri'))
await client.connect()
const db = client.db()
const stuff = db.collection('AllTheStuff')
const record = {
type: "ThisAndThat",
lastUpdated: new Date().getTime()
}
const query = { type: "ThisAndThat" }
const options = { upsert: true }
const result = await stuff.replaceOne(query, record, options)
And now all your cats are sleep silent tonight. Hopefully this lowers the level of unchallenged insanity in the world, or helps you in your quest, whichever suits your taste in achievement. :)
import { MongoClient } from 'mongodb';
just imports type definition from node_modules/#types/mongodb/index.d.ts
import * as mongodb from 'mongodb';
imports everything from node_modules/mongodb/index.js and its the same as
let mongodb = require('mongodb');
Try this:
import { default as mongodb } from 'mongodb';
let MongoClient = mongodb.MongoClient;
Edit
As Elihu pointed out in the comment below, the additional integration of #types/mongo is now deprecated and is no longer needed as the mongo-package now comes with types per default.
npm install --save mongodb is therefore sufficient.
Original Answer
As mkalmo suggested you can import the mongodb types:
Step 1: Install via the npm mongodb types package
npm install --save #types/mongodb
Step 2: Use it!
import mongodb from "mongodb";
const MongoClient = mongodb.MongoClient;
This works for me:
import mongodb from 'mongodb'
const { MongoClient } = mongodb