So basically with my app i have react js and node js. Everything works fine but I have a section of the web app that makes a post request to the node backend to get data related to getting an array of items through the ebay api. This worked fine during development but when I tried to do the same thing after deployment, I get a 404 error
Response {type: "basic", url: "https://udabasili.herokuapp.com/api/ebay", redirected: false, status: 404, ok: false, …}
The client link is https://udabasili.herokuapp.com/
The server link is https://ud-portfolio-app.herokuapp.com/
I even used postman to send a post request to the node domain deployed on heroku and it works, so the problem seems to be from the react js app
The app is a quite big but basically i have the node and react on two different domains with have the static.json linking the node serveri have deployed already to react js using proxy
The important sections of the app involved :
STATIC.JSON
{
"root":"build/",
"routes":{
"/**":"index.html"
},
"proxies":{
"/api/":{
"origin":"https://ud-portfolio-app.herokuapp.com/"
}
}
}
NODE.JS
const express = require("express");
const app = express()
const path = require("path")
const Ebay = require('ebay-node-api');
const cors = require("cors")
const bodyParser = require("body-parser");
const PORT = process.env.PORT || 8081;
let access_token = '';
let ebay = new Ebay({
clientID: '******************',
clientSecret: '*******************',
body: {
grant_type: 'client_credentials',
scope: 'https://api.ebay.com/oauth/api_scope'
}
});
app.use(cors());
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
// An api endpoint that returns a short list of items
app.post('/api/ebay', (req,res) => {
const item = req.body.itemName;
ebay.findItemsByKeywords({
keywords: `${item} movie`,
}).then((data) => {
res.json(data[0].searchResult[0].item);
}, (error) => {
console.log(error);
});
});
app.listen(PORT);
REST API SECTION
At this section I fetch the two apis . The youtube one work but the ebay has the 404 error
function fetchProducts(name) {
const itemName = name;
const ebayApi = fetch("/api/ebay",
{
method: "POST",
cache: "no-cache",
headers:{
"Content-Type": "application/json"
},
body:JSON.stringify({itemName:itemName})
}
);
const youtubeApi = fetch(`https://www.googleapis.com/youtube/v3/search?part=snippet&q=${name}%20movie%20trailer&key=**************`);
return (dispatch) => {
Promise.all([ebayApi, youtubeApi])
.then( values => Promise.all(values.map(value =>{
console.log(value);
return value.json()})
))
.then(res => {
const youtube = `https://www.youtube.com/embed/${res[1].items[0].id.videoId}?autoplay=1&showinfo=0&rel=0`;
return (res[0], res[1].items[0].id.videoId)
})
.catch((error) => {
console.log(error);
});
};
}
export default fetchProducts;
CLIENT PACKAGE.JSON
{
"name": "client",
"version": "0.1.0",
"proxy": "http://localhost:8081",
"private": true,
"dependencies": {
"babel-eslint": "^10.0.3",
"d3": "^5.12.0",
"ebay-node-api": "^2.7.2",
"flag-icon-css": "^3.4.5",
"font-awesome": "^4.7.0",
"node-sass": "^4.13.0",
"prop-types": "^15.7.2",
"react": "^16.11.0",
"react-dom": "^16.11.0",
"react-redux": "^7.1.1",
"react-router-dom": "^5.1.2",
"react-scripts": "3.2.0",
"react-transition-group": "^4.3.0",
"redux": "^4.0.4",
"redux-persist": "^6.0.0",
"redux-thunk": "^2.3.0",
"topojson-client": "^3.0.1",
"youtube-api-search": "^0.0.5"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"lint": "eslint --ext .js --ext .jsx ."
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"eslint": "^6.6.0",
"eslint-config-airbnb": "^18.0.1",
"eslint-plugin-import": "^2.18.2",
"eslint-plugin-jsx-a11y": "^6.2.3",
"eslint-plugin-react": "^7.16.0",
"eslint-plugin-react-hooks": "^1.7.0"
}
}
Related
I am trying to seed my db and this issue is preventing that. It keeps saying "Inventory.create is not a function
at seed". I am not sure if this is a syntactical issue, a logistical problem or even a dependency issue so please point me in the wrong direction.
The tech stack that I am using is Express, Node.js, Sequelize, PostgreSQL
My files are structured as such:
--script
-seed.js
--server
-api
-db
-Model.js
-index.js
-db.js
-app.js
-index.js
Model.js
const db = require('./db');
const Model = db.define('model', {
name: {
type: Sequelize.STRING,
allowNull: false,
},
total: {
type: Sequelize.FLOAT,
allowNull: false,
},
})
module.export = Model;
index.js
const db = require('./db')
const Inventory = require('./Inventory')
module.exports = {
db,
models: {
Inventory,
},
}
db.js
const Sequelize = require('sequelize')
const pkg = require('../../package.json')
const databaseName = pkg.name + (process.env.NODE_ENV === 'test' ? '-test' : '')
if(process.env.LOGGING === 'true'){
delete config.logging
}
if(process.env.DATABASE_URL){
config.dialectOptions = {
ssl: {
rejectUnauthorized: false
}
};
}
const db = new Sequelize(
process.env.DATABASE_URL || `postgres://localhost:5432/${databaseName}`, {
logging: false,
})
module.exports = db
seed.js
'use strict'
const {db, models: {Model}} = require('../server/db')
async function seed() {
await db.sync({ force: true })
console.log('db synced!')
// Creating Inventory
const stock = await Promise.all([
Model.create({ name: 'First', amount: 200 }),
Model.create({ name: 'Second', amount: 200 }),
])
console.log(`seeded successfully`)
}
async function runSeed() {
console.log('seeding...')
try {
await seed()
} catch (err) {
console.error(err)
process.exitCode = 1
} finally {
console.log('closing db connection')
await db.close()
console.log('db connection closed')
}
}
if (module === require.main) {
runSeed()
}
module.exports = seed
I included this just in case
package.json
{
"name": "ShopifyInventory",
"version": "1.0",
"description": "Simple backend heavy app for inventory management",
"main": "app.js",
"scripts": {
"build": "webpack",
"build:dev": "npm run build -- --watch --mode=development",
"seed": "node script/seed.js",
"start": "node server"
},
"dependencies": {
"axios": "^0.21.1",
"bcrypt": "^5.0.0",
"compression": "^1.7.3",
"express": "^4.18.1",
"history": "^4.9.0",
"jsonwebtoken": "^8.5.1",
"morgan": "^1.9.1",
"pg": "^8.7.3",
"pg-hstore": "^2.3.4",
"react": "^18.1.0",
"react-dom": "^18.1.0",
"react-router-dom": "^6.3.0",
"sequelize": "^6.19.2"
},
"author": "Galilior :)",
"devDependencies": {
"#babel/core": "^7.17.12",
"#babel/preset-react": "^7.17.12",
"babel-loader": "^8.2.5",
"webpack": "^5.72.1",
"webpack-cli": "^4.9.2"
}
}
My project has 2 folders: client(next.js with custom server) and server(node.js).
I have uploaded it in a Ubuntu 20.04 server and build next.js project in client folder. it works.
I have recently changed some pages of next.js and uploaded to client folder by "sudo git pull".
Now I would like to run "npm run build" to build next.js again, but it gives Error:
warn - No ESLint configuration detected. Run next lint to begin setup
Build error occurred
Error: > Build directory is not writeable. https://nextjs.org/docs/messages/build-dir-not-writeable
at /home/skadmin/client/node_modules/next/dist/build/index.js:275:19
at async Span.traceAsyncFn (/home/skadmin/client/node_modules/next/dist/telemetry/trace/trace.js:60:20)
at async Object.build [as default] (/home/skadmin/client/node_modules/next/dist/build/index.js:77:25)
info - Creating an optimized production build
==========My Custom server is:
'''
const express = require('express')
const next = require('next')
const { createProxyMiddleware } = require('http-proxy-middleware')
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app
.prepare()
.then(() => {
const server = express()
// apply proxy in dev mode
if (dev) {
server.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:8000',
changeOrigin: true,
})
)
}
server.all('*', (req, res) => {
return handle(req, res)
})
server.listen(3000, (err) => {
if (err) throw err
console.log('> Ready on http://localhost:8000')
})
})
.catch((err) => {
console.log('Error', err)
})
'''
=======================package.json is=>:
'''
{
"name": "client",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "node server.js",
"build": "next build",
"start": "NODE_ENV=production node server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"#ant-design/icons": "^4.5.0",
"#glidejs/glide": "^3.4.1",
"#material-ui/core": "^4.11.4",
"#material-ui/icons": "^4.11.2",
"#persian-tools/persian-tools": "^3.0.1",
"antd": "^4.13.1",
"axios": "^0.21.4",
"express": "^4.17.1",
"http-proxy-middleware": "^2.0.0",
"lodash": "^4.17.21",
"moment-jalaali": "^0.9.2",
"multer": "^1.4.4",
"next": "^11.1.3",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-icons": "^4.2.0",
"react-image-file-resizer": "^0.4.7",
"react-markdown": "^6.0.2",
"react-scroll": "^1.8.2",
"react-toastify": "^7.0.4",
"reactstrap": "^8.9.0",
"swiper": "^7.4.1"
}
}
'''
Please help me, what should I do?
I am seeing this error in my index.js file in VSC which looks to be caused by the app.post request.
I've attempted different parsing options in regards to eslint and emca but still aren't getting anywhere.
Appreciate any input.
Parsing error: Unexpected token => eslint
index.js
const functions = require("firebase-functions");
const express = require("express");
const cors = require("cors");
const stripe = require("stripe")("hidden");
// Setting Up the API
// - App Config
const app = express();
// - Middlewares
app.use(cors({ origin: true }));
app.use(express.json());
// - API routes
app.get("/", (request, response) => response.status(200).send("hello world"));
app.post("/payments/create", async (request, response) => {
const total = request.query.total;
console.log("Payment Request Recieved for this amount >>> ", total);
const paymentIntent = await stripe.paymentIntents.create({
amount: total, // subunits of the currency
currency: "usd",
});
// OK - Created
response.status(201).send({
clientSecret: paymentIntent.client_secret,
});
});
// - Listen command
exports.api = functions.https.onRequest(app);
This is my package.json
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"lint": "eslint .",
"serve": "firebase emulators:start --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "14"
},
"main": "index.js",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.17.1",
"firebase-admin": "^9.8.0",
"firebase-functions": "^3.14.1",
"stripe": "^8.174.0"
},
"devDependencies": {
"#babel/core": "^7.15.5",
"#babel/eslint-parser": "7.15.4",
"eslint": "^7.6.0",
"eslint-config-google": "^0.14.0",
"eslint-plugin-react": "^7.25.1",
"firebase-functions-test": "^0.2.0"
},
"private": true
}
And then this is my .eslintrc.js file
module.exports = {
root: true,
env: {
es6: true,
node: true,
},
extends: [
"eslint: recommended",
"google",
"plugin: react/recommended",
],
rules: {
quotes: ["error", "double"],
},
};
Seems like you're missing parser: #babel/eslint-parser from your eslintrc
when i tried to generate a build and serve SSR project with angular i got this error
C:\Projects\cloud_market_ssr\client\dist\market\server\main.js:72623
var requestFn = window.requestAnimationFrame||getPrefixed('RequestAnimationFrame') || timeoutDefer;
ReferenceError: window is not defined
at C:\Projects\cloud_market_ssr\client\dist\market\server\main.js:72623:19
at C:\Projects\cloud_market_ssr\client\dist\market\server\main.js:72404:11
at Object.4R65 (C:\Projects\cloud_market_ssr\client\dist\market\server\main.js:72406:2)
at __webpack_require__ (C:\Projects\cloud_market_ssr\client\dist\market\server\main.js:26:30)
at Module.ZeVW (C:\Projects\cloud_market_ssr\client\dist\market\server\main.js:223603:65)
at __webpack_require__ (C:\Projects\cloud_market_ssr\client\dist\market\server\main.js:26:30)
at Module.PCNd (C:\Projects\cloud_market_ssr\client\dist\market\server\main.js:178377:126)
at __webpack_require__ (C:\Projects\cloud_market_ssr\client\dist\market\server\main.js:26:30)
at Module.ZAI4 (C:\Projects\cloud_market_ssr\client\dist\market\server\main.js:221439:79)
at __webpack_require__ (C:\Projects\cloud_market_ssr\client\dist\market\server\main.js:26:30)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
Process finished with exit code 1
this is the packages that i installed and they perfectly work
{
"name": "market",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build --prod",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e",
"dev:ssr": "ng run market:serve-ssr",
"serve:ssr": "node dist/market/server/main.js",
"build:ssr": "npm run build && ng run market:server:production",
"full:ssr": "npm run build:ssr && npm run dev:ssr && npm run serve:ssr",
"prerender": "ng run market:prerender"
},
"private": true,
"dependencies": {
"#angular/animations": "^11.2.13",
"#angular/cdk": "^11.2.12",
"#angular/common": "^11.2.13",
"#angular/compiler": "^11.2.13",
"#angular/core": "^11.2.13",
"#angular/flex-layout": "^11.0.0-beta.33",
"#angular/forms": "^11.2.13",
"#angular/material": "^11.2.12",
"#angular/platform-browser": "^11.2.13",
"#angular/platform-browser-dynamic": "^11.2.13",
"#angular/platform-server": "^11.2.13",
"#angular/pwa": "^0.1102.12",
"#angular/router": "^11.2.13",
"#angular/service-worker": "^11.2.13",
"#nguniversal/express-engine": "^11.2.1",
"#nicky-lenaers/ngx-scroll-to": "^9.0.0",
"core-js": "^2.5.4",
"cors": "^2.8.5",
"domino": "^2.1.6",
"echarts": "^4.2.0-rc.2",
"echarts-gl": "^1.1.1",
"edit-json-file": "^1.6.0",
"express": "^4.15.2",
"font-awesome": "^4.7.0",
"hammerjs": "^2.0.8",
"jalali-moment": "^3.2.1",
"jquery": "^3.4.1",
"leaflet": "^1.7.1",
"leaflet-arc": "^1.0.2",
"localforage": "^1.5.0",
"localstorage-polyfill": "^1.0.1",
"mock-browser": "^0.92.14",
"moment-jalaali": "~0.9.2",
"ngforage": "^6.0.0",
"ngx-image-compress": "^11.0.3",
"ngx-image-zoom": "^0.6.0",
"ngx-owl-carousel-o": "^5.0.0",
"ngx-pagination": "^5.1.0",
"ngx-slick-carousel": "~0.5.1",
"rxjs": "^6.5.3",
"sass": "^1.32.6",
"slick-carousel": "~1.8.1",
"webpack-node-externals": "^3.0.0",
"zone.js": "~0.11.4"
},
"devDependencies": {
"#angular-devkit/build-angular": "~0.1002.0",
"#angular/cli": "^11.2.12",
"#angular/compiler-cli": "^11.2.13",
"#angular/language-service": "^11.2.13",
"#nguniversal/builders": "^10.1.0",
"#types/express": "^4.17.0",
"#types/jasmine": "~3.7.2",
"#types/jasminewd2": "~2.0.9",
"#types/node": "~14.14.44",
"codelyzer": "~6.0.2",
"eslint": "~7.26.0",
"jasmine-core": "~3.7.1",
"jasmine-spec-reporter": "~7.0.0",
"karma": "~6.3.2",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage-istanbul-reporter": "~3.0.3",
"karma-jasmine": "~4.0.1",
"karma-jasmine-html-reporter": "^1.6.0",
"protractor": "^7.0.0",
"ts-node": "~9.1.1",
"typescript": "~4.0.6"
}
}
and this is my server.ts
import 'zone.js/dist/zone-node';
import * as express from 'express';
import { ngExpressEngine } from '#nguniversal/express-engine';
import { join } from 'path';
///Handle Error local storage & document & window not defined
const MockBrowser = require('mock-browser').mocks.MockBrowser;
const mock = new MockBrowser();
const cors = require('cors');
const exp = require('express');
const application = exp();application.use(cors());
const domino = require("domino");
const fs = require("fs");
const path = require("path");
const templateA = fs
.readFileSync(path.join("dist/browser", "index.html"))
.toString();
const win = domino.createWindow(templateA);
win.Object = Object;
win.Math = Math;
import 'localstorage-polyfill';
global['localStorage'] = localStorage;
global["window"] = mock.getWindow();
global["document"] = mock.getDocument();
global["branch"] = null;
global["object"] = win.object;
global['navigator'] = mock.getNavigator();
Object.defineProperty(document.body.style, 'transform', {
value: () => {
return {
enumerable: true,
configurable: true
};
},
});
//////////////////////////////////////
import { APP_BASE_HREF } from '#angular/common';
import { AppServerModule } from './src/main.server';
import { existsSync } from 'fs';
// The Express app is exported so that it can be used by serverless Functions.
export function app(): express.Express {
const server = express();
const distFolder = join(process.cwd(), 'dist/client/browser');
const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index';
// Our Universal express-engine (found # https://github.com/angular/universal/tree/master/modules/express-engine)
server.engine('html', ngExpressEngine({
bootstrap: AppServerModule,
}));
server.set('view engine', 'html');
server.set('views', distFolder);
// Example Express Rest API endpoints
// server.get('/api/**', (req, res) => { });
// Serve static files from /browser
server.get('*.*', express.static(distFolder, {
maxAge: '1y'
}));
// All regular routes use the Universal engine
server.get('*', (req, res) => {
res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
});
return server;
}
function run(): void {
const port = process.env.PORT || 5050;
// Start up the Node server
const server = app();
server.listen(port, () => {
console.log(`Node Express server listening on http://localhost:${port}`);
});
}
// Webpack will replace 'require' with '__webpack_require__'
// '__non_webpack_require__' is a proxy to Node 'require'
// The below code is to ensure that the server is run only when not requiring the bundle.
declare const __non_webpack_require__: NodeRequire;
const mainModule = __non_webpack_require__.main;
const moduleFilename = mainModule && mainModule.filename || '';
if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
run();
}
const nodeExternals = require('webpack-node-externals');
module.exports = {
externals: [nodeExternals()],
// etc configs here
}
export * from './src/main.server';
You are probably using some library or component in which needs the window to be rendered, as example, a chart.
Go over your code base and see if anything could be using the window and that doesnt need to be rendered server side.
Once you find it, use the platform id injector from angular to check wheter you are on the browser or the server, if it is on server do not render said component.
I am trying to create a seeder file in nestjs, the problem is when I run the project using start:dev, somehow nestjs also start seed.ts file with main.ts file. How can I make nestjs not start seed file when I run the project either on prod/dev but seed must be called only when I run the seed script.
Here is the seed.ts code
import { NestFactory } from '#nestjs/core'
import { Logger } from '#nestjs/common'
import { SeederModule } from './database/seeder.module'
import { Seeder } from './database/seeder'
async function bootstrap() {
NestFactory.createApplicationContext(SeederModule)
.then((appContext) => {
const logger = appContext.get(Logger)
const seeder = appContext.get(Seeder)
seeder
.seedRoles()
.then(() => {
logger.debug('Seeding Roles complete!')
})
.catch((error) => {
logger.error('Seeding Roles failed!')
throw error
})
seeder
.seedAdmin()
.then(() => {
logger.debug('Seeding Admin complete!')
})
.catch((error) => {
logger.error('Seeding Admin failed!')
throw error
})
.finally(() => appContext.close())
})
.catch((error) => {
throw error
})
}
bootstrap()
Here is the main.ts file for nestJS
import { Logger, ValidationPipe } from '#nestjs/common'
import { NestFactory } from '#nestjs/core'
import { AppModule } from './modules/app/app.module'
async function bootstrap() {
const app = await NestFactory.create(AppModule)
app.enableCors()
const port = process.env.PORT || 3000
app.useGlobalPipes(new ValidationPipe())
await app
.listen(port)
.then(() => {
Logger.log(`App listening on port ${port}`)
})
.catch((err) => {
Logger.log(`Error while connecting to port ${port}`, err)
})
}
bootstrap()
And here is the package.json file
{
"name": "jugg-website",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "link-module-alias && nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json",
"seed": "ts-node -r tsconfig-paths/register src/seed.ts"
},
"dependencies": {
"#nestjs/common": "^7.6.13",
"#nestjs/core": "^7.6.13",
"#nestjs/jwt": "^7.2.0",
"#nestjs/passport": "^7.1.5",
"#nestjs/platform-express": "^7.6.13",
"#nestjs/typeorm": "^7.1.5",
"class-transformer": "^0.4.0",
"class-validator": "^0.13.1",
"config": "^3.3.6",
"link-module-alias": "^1.2.0",
"passport": "^0.4.1",
"pg": "^8.5.1",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^6.6.6",
"typeorm": "^0.2.32"
},
"devDependencies": {
"#nestjs/cli": "^7.5.6",
"#nestjs/schematics": "^7.2.7",
"#nestjs/testing": "^7.6.13",
"#types/express": "^4.17.11",
"#types/jest": "^26.0.20",
"#types/node": "^14.14.31",
"#types/supertest": "^2.0.10",
"#typescript-eslint/eslint-plugin": "^4.15.2",
"#typescript-eslint/parser": "^4.15.2",
"eslint": "^7.20.0",
"eslint-config-prettier": "^8.1.0",
"eslint-plugin-prettier": "^3.3.1",
"jest": "^26.6.3",
"prettier": "^2.2.1",
"supertest": "^6.1.3",
"ts-jest": "^26.5.2",
"ts-loader": "^8.0.17",
"ts-node": "^9.1.1",
"tsconfig-paths": "^3.9.0",
"typescript": "^4.1.5"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}
you can try setting KeepConnectionAlive option to true in typeOrm
configuration in the app.module file
https://github.com/nestjs/typeorm/issues/61
I was getting this error when running e2e tests. I found that the default nestjs template sets up the e2e tests with a beforeEach like this:
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
But since I had more than one test in the spec file (I'm a newbie to node.js dev so not sure whether this is the right thing to do or not, but regardless...), what was happening was the app was being initialised once per test which meant it was attempting to create multiple connections to the database.
The solution was quite simple. Change the beforeEach to beforeAll
beforeAll(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
And don't forget to close the app when the tests are done
afterAll(async () => {
await app.close();
});
In my case, the problem was in my main.ts file. I ran my module with the TypeORM twice without noticing, because I was trying access my ConfigService so that I could use environment variables for some other service than my TypeORM database connection.
main.ts that causes the error:
...
async function bootstrap(): Promise<void> {
// the next line actually initiates a DB connection
const appContext = await NestFactory.createApplicationContext(MailModule);
const configService = appContext.get<ConfigService>(ConfigService);
// by now, we already established a DB connection, so trying to
// reinstantiate the connection will cause the error
const app = await NestFactory.createMicroservice<MicroserviceOptions>(
MailModule,
{
transport: Transport.REDIS,
options: {
port: configService.get<number>('REDIS.PORT'),
host: configService.get<string>('REDIS.HOST'),
},
},
);
await app.listen();
}
bootstrap();
The solution:
...
async function bootstrap(): Promise<void> {
const appContext = await NestFactory.createApplicationContext(MailModule);
// we close the redundant connection before we mount the app.
await getConnection('default').close();
const configService = appContext.get<ConfigService>(ConfigService);
const app = await NestFactory.createMicroservice<MicroserviceOptions>(
MailModule,
{
transport: Transport.REDIS,
options: {
port: configService.get<number>('REDIS.PORT'),
host: configService.get<string>('REDIS.HOST'),
},
},
);
await app.listen();
}
bootstrap();