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
Related
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 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();
I have created a react app, and I have connected the mongoDB database, now the problem is whenever I start the node server the server gets started as well as the mongodb database, but most of the time the mongoDB database shows timeout error.
I am adding image, have a look through it for the error as well as I am showing my pacakage.json file.
{
"name": "ewk",
"version": "1.0.0",
"description": "abcd",
"main": "server.js",
"type": "module",
"scripts": {
"start": "node backend/server",
"server": "nodemon backend/server",
"client": "npm start --prefix frontend",
"dev": "concurrently \"npm run server\" \"npm run client\"",
"data:import": "node backend/seeder",
"data:destroy": "node backend/seeder -d"
},
"author": "xyz",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"express-async-handler": "^1.1.4",
"mongoose": "^5.11.13"
},
"devDependencies": {
"concurrently": "^5.3.0",
"nodemon": "^2.0.7"
}
}
This is my database configuration code:
import mongoose from 'mongoose';
const connectDB = async () => {
try{
const conn = await mongoose.connect(process.env.MONGO_URI, {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true
})
console.log(`MongoDB Connected: ${conn.connection.host}`)
} catch (error){
console.error(`Error: ${error.message}`)
process.exit(1)
}
}
export default connectDB
I have added the uri which I added in env file:
mongodb+srv://abj:*******#ewfsa-cluster.hbwdr.mongodb.net/EWFSA?retryWrites=true&w=majority
I have the following webhook, and it is listening for a payment provider API to update the status of an order once it is 'paid'. In logs for Firebase Functions, I get the console log Payment status paid meaning that I get the update of the order correctly. However, when I try to call the function responsible for updating Firestore, I get the following:
#firebase/firestore: Firestore (7.16.0): Connection GRPC stream error. Code: 13 Message: 13 INTERNAL: Received RST_STREAM with code 2
exports.webhooks = functions.https.onRequest(function (req, res) {
mollieClient.payments
.get(req.body.id)
.then((payment) => {
console.log("Payment status " + payment.status);
if (payment.isPaid()) {
updateOrderStatusPaid(req.body.id);
return null;
}
return null;
})
.catch((error) => {
res.send(error);
});
console.log("Request body " + req.body);
});
function updateOrderStatusPaid(orderId) {
firebase
.firestore()
.collection("orders")
.where("paymentId", "==", orderId)
.update({
status: payment.status
})
.then(function () {
console.log("Success");
return null;
})
.catch(function (error) {
console.log("Error " + error);
});
}
Here is my package.json file
{
"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": "8"
},
"dependencies": {
"#mollie/api-client": "^3.2.4",
"axios": "^0.20.0",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"firebase": "^7.16.0",
"firebase-admin": "^8.10.0",
"firebase-functions": "^3.6.1",
"grpc": "^1.24.4"
},
"devDependencies": {
"eslint": "^5.12.0",
"eslint-plugin-promise": "^4.0.1",
"firebase-functions-test": "^0.2.0"
},
"private": true
}
I cannot find anything specific to this problem. I am already using Firestore on my server side so there is no problem with initialization of Firebase. Maybe somebody knows where the problem might be or suggest something I should do to solve this. Thank you!
The closest link to this problem is https://github.com/googleapis/nodejs-datastore/issues/679 where still there is not answer.
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"
}
}