google firebase function tutorial unexpected token => - node.js

I have done some googling and haven't found an answer to my question. I am following the tutorial for google firebase functions here and have copied index.js exactly from the GitHub repository linked on the tutorial as well as copying the code in 'chunks' by following the tutorial and I get this error after running firebase deploy --only functions
error Parsing error: Unexpected token =>
which references this function:
exports.addMessage = (functions.https.onRequest(async (req, res) => { //This line
// [END addMessageTrigger]
// Grab the text parameter.
const original = req.query.text;
// [START adminSdkAdd]
// Push the new message into Firestore using the Firebase Admin SDK.
const writeResult = await admin.firestore().collection('messages').add({ original: original });
// Send back a message that we've successfully written the message
res.json({ result: `Message with ID: ${writeResult.id} added.` });
// [END adminSdkAdd]
}));
Link to index.js file used in tutorial
My eslintrc.js file:
module.exports = {
root: true,
env: {
es6: true,
node: true,
},
extends: [
"eslint:recommended",
"google",
],
rules: {
quotes: ["error", "double"],
},
};

Async functions and await keyword were added in ECMAScript 2017. You need to set ecmaVersion to 8 in your ESLint config.
module.exports = {
root: true,
env: {
es6: true,
node: true,
},
extends: [
"eslint:recommended",
"google",
],
parserOptions: {
ecmaVersion: 8
},
rules: {
quotes: ["error", "double"],
},
};

Related

Building a NodeJS app with file based db using webpack, and Typescript

The problem
I am using Phaser 3 html5 framework that runs on webpack. I am trying to make an offline game that would run on desktop or mobile apps, not a browser game, so I don't want to use the local storage or other in-memory databases. The players should be able to save the game, and the game would be stored in a DB file. I am trying to find the best solution to relational DB in my app.
What I tried:
I tried implementing sqlite3, better-sqlite3, postgres and few other options, but nothing seems to be working. The client-side can't handle databases and is throwing errors. I also tried browserify to bundle sqlite3 imports into binary and call it from the index.html, but that also gave me errors:
(terminal) .src/ browserify server.js > bundle.js
.src/server.js:
const db = require('better-sqlite3')('game.db');
.src/bundle.js:
.src/index.html:
<script src="bundle.js></script>
error:
bundle.js:5638 Uncaught TypeError: The "original" argument must be of type Function
at promisify (bundle.js:5638:11)
at Object.<anonymous> (bundle.js:146:18)
at Object.<anonymous> (bundle.js:209:4)
at 4.../util (bundle.js:209:17)
at o (bundle.js:1:265)
at bundle.js:1:316
at Object.<anonymous> (bundle.js:74:29)
at Object.<anonymous> (bundle.js:88:4)
at 1.../../../../../../../usr/local/lib/node_modules/browserify/node_modules/is-buffer/index.js (bundle.js:88:17)
at o (bundle.js:1:265)
I would like to know if there is an easy way to create and use a relational database like SQLite3 or Postgres with NodeJS without dealing with browser limitations since the app won't run in the browser eventually. Please let me know if you have any insights on this. I am also sharing my webpack.config and tsconfig files for reference:
webpack config file
const path = require("path");
const webpack = require("webpack");
const { merge } = require("webpack-merge");
const baseConfig = require("./webpack.config.base.js");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const CopyPlugin = require("copy-webpack-plugin");
const LoadablePlugin = require("#loadable/webpack-plugin");
const clientConfig = {
entry: {
main: "./src/index.ts"
},
name: "client",
devtool: 'inline-source-map',
optimization: {
splitChunks: {
cacheGroups: {
phaser: {
test: /[\\/]node_modules[\\/]phaser[\\/]/,
name: "phaser",
chunks: "all",
},
}
}
},
output: {
path: path.resolve(__dirname, 'www'),
filename: "main.js"
},
module: {
rules: [
{
test: /\.tsx?$/,
use: "ts-loader",
exclude: /node_modules/,
},
{
test: /\.json/,
type: "asset/resource",
exclude: /node_modules/,
},
],
},
devServer: {
historyApiFallback: true,
allowedHosts: 'all',
static: {
directory: path.resolve(__dirname, "./src"),
},
open: true,
hot: true,
port: 8080,
},
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, "src/index.html"),
minify: false
}),
new CleanWebpackPlugin(),
new LoadablePlugin({
outputAsset: false, // to avoid writing loadable-stats in the same output as client
writeToDisk: true,
filename: `${__dirname}/loadable-stats.json`,
}),
new webpack.LoaderOptionsPlugin({
// test: /\.xxx$/, // may apply this only for some modules
options: {
ts: {
configFileName : 'tsconfig.client.json'
}
}
}),
new CopyPlugin({
patterns: [
{
from: "static",
globOptions: {
// asset pack files are imported in code as modules
ignore: ["**/publicroot", "**/*-pack.json"]
}
}
]
}),
]
};
module.exports = merge(baseConfig, clientConfig);
tsconfig file
{
"extends": "./tsconfig.json",
"skipLibCheck": true,
"compilerOptions": {
"module": "ES6",
"target": "ES2022",
"outDir": "./www",
"rootDir": "./src",
"esModuleInterop": true,
"typeRoots": [
"node_modules/#types",
"node_module/phaser/types"
],
"types": [
"phaser", "node"
],
},
"include": [
"src/**/*",
"types/**/*"
]
}

Jest Modules Do Not Import Correctly

Dealing with modules in Jest has been a nightmare.
Aside from all the other issues encountered, there is one I have yet to be able to work through.
It looks as certain imports are getting imported incorrectly.
Consider the following trivial example
import * as jp from 'jsonpath'
console.log('paths: ' + jp.paths)
when running my app code in the browser, this prints
paths: function(obj, string, count) {
assert.ok(obj instanceof Object, "obj needs to be an object");
assert.ok(string, "we need a path");
var results = this.nodes(obj, string, count)
.map(function(r) { return r.path });
return results;
}
when running the same code from a Jest test, I get:
console.log
paths: undefined
upon debugging the test and inspecting the jp object in the debugger, I see:
Needless to say this does not look correct. When running console.log(jp) from the browser, I see
It seems like Jest is screwing up the module prototype somehow.
My jest.config.js:
const esModules = ['quasar/lang', 'lodash-es'].join('|');
/* eslint-env node */
module.exports = {
globals: {
__DEV__: true,
// TODO: Remove if resolved natively https://github.com/vuejs/vue-jest/issues/175
'vue-jest': {
pug: { doctype: 'html' },
},
},
setupFilesAfterEnv: ['<rootDir>/test/jest/jest.setup.ts'],
// noStackTrace: true,
// bail: true,
// cache: false,
// verbose: true,
// watch: true,
collectCoverage: false,
coverageDirectory: '<rootDir>/test/jest/coverage',
collectCoverageFrom: [
'<rootDir>/src/**/*.vue',
'<rootDir>/src/**/*.js',
'<rootDir>/src/**/*.ts',
'<rootDir>/src/**/*.jsx',
'<rootDir>/src/**/*.tsx',
],
coveragePathIgnorePatterns: ['/node_modules/', '.d.ts$'],
coverageThreshold: {
global: {
// branches: 50,
// functions: 50,
// lines: 50,
// statements: 50
},
},
testMatch: [
// Matches tests in any subfolder of 'src' or into 'test/jest/__tests__'
// Matches all files with extension 'js', 'jsx', 'ts' and 'tsx'
'<rootDir>/test/jest/__tests__/**/*.(spec|test).+(ts|js)?(x)',
'<rootDir>/src/**/*.jest.(spec|test).+(ts|js)?(x)',
],
// Extension-less imports of components are resolved to .ts files by TS,
// grating correct type-checking in test files.
// Being 'vue' the first moduleFileExtension option, the very same imports
// will be resolved to .vue files by Jest, if both .vue and .ts files are
// in the same folder.
// This guarantee a great dev experience both for testing and type-checking.
// See https://github.com/vuejs/vue-jest/issues/188#issuecomment-620750728
moduleFileExtensions: ['vue', 'js', 'jsx', 'json', 'ts', 'tsx'],
moduleNameMapper: {
'^quasar$': 'quasar/dist/quasar.common.js',
'^~/(.*)$': '<rootDir>/$1',
'^src/(.*)$': '<rootDir>/src/$1',
'^app/(.*)$': '<rootDir>/$1',
'^components/(.*)$': '<rootDir>/src/components/$1',
'^layouts/(.*)$': '<rootDir>/src/layouts/$1',
'^pages/(.*)$': '<rootDir>/src/pages/$1',
'^assets/(.*)$': '<rootDir>/src/assets/$1',
'^boot/(.*)$': '<rootDir>/src/boot/$1',
'.*css$': '#quasar/quasar-app-extension-testing-unit-jest/stub.css',
},
transform: {
// See https://jestjs.io/docs/en/configuration.html#transformignorepatterns-array-string
[`^(${esModules}).+\\.js$`]: 'babel-jest',
'^.+\\.(ts|js|html)$': 'ts-jest',
// vue-jest uses find-babel-file, which searches by this order:
// (async) .babelrc, .babelrc.js, package.json, babel.config.js
// (sync) .babelrc, .babelrc.js, babel.config.js, package.json
// https://github.com/tleunen/find-babel-config/issues/33
'.*\\.vue$': 'vue-jest',
'.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$':
'jest-transform-stub',
},
transformIgnorePatterns: [`node_modules/(?!(${esModules}))`],
snapshotSerializers: ['<rootDir>/node_modules/jest-serializer-vue'],
testEnvironment: 'jsdom'
};
Any suggestions on how to resolve this?
Thank you.

Cannot find module 'sanitize.css/page.css'

While building the gatsby project, I faced this kind of error.
yarn develop
ERROR #98123 WEBPACK
Generating development JavaScript bundle failed
Cannot find module 'sanitize.css/page.css'
Require stack:
- D:\UpworkJobs\Nate\dci-gatsby-importexport\node_modules\postcss-normalize\dist\index.cjs.js
File: src\css\preview.css
failed Building development bundle - 366.725s
Here is a screenshot of the error log.
These kinds of errors occur even if I removed all CSS codes from the style files.
It seems importing CSS files is not working. If I didn't import the CSS files, the errors go away.
Here are all codes of gatsby-config.js
let systemvars = false;
if (process.env.NODE_ENV === "production") {
systemvars = true;
}
require("dotenv").config({
path: `.env.${process.env.NODE_ENV}`,
systemvars
});
// Gatsby automatically sets NODE_ENV to `development` or `production` when running `gatsby develop` or `gatsby build`, respectively.
// Thus make sure you have .env.development or .env.production setup (unless your CI/build env vars are already set globally)
const AliasConfig = require("./alias.config.js");
module.exports = {
siteMetadata: {
title: `DCI DigiGuide Print`,
description: `DCI DigiGuide Printable Version`,
author: `#designbycosmic`,
siteUrl: process.env.SITE_URL,
},
plugins: [
//
// * App Functionality Plugins
//
// eslint plugin
{
resolve: "gatsby-plugin-eslint",
options: {
test: /\.js$|\.jsx$/,
exclude: /(node_modules|.cache|public)/,
stages: ["develop"],
options: {
maxWarnings: undefined,
emitWarning: true,
failOnError: false,
failOnWarning: false,
},
},
},
// allows content to be placed in head
`gatsby-plugin-react-helmet`,
// adds web manifest for some pwa functionality
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `gatsby-dci-digiguide-print`,
short_name: `DigiGuidePrint`,
start_url: `/`,
background_color: `#222c47`,
theme_color: `#222c47`,
display: `minimal-ui`,
icon: `./src/images/favicon.png`, // This path is relative to the root of the site.
},
},
// allow alias imports
{
resolve: "gatsby-plugin-alias-imports",
options: {
alias: AliasConfig.map,
extensions: AliasConfig.extensions,
},
},
// inline svgs instead of converting them to base64
{
resolve: "gatsby-plugin-react-svg",
options: {
rule: {
include: /svg/,
},
},
},
`gatsby-plugin-postcss`,
`gatsby-plugin-material-ui`,
// Craft CMS configuration
{
resolve: `gatsby-source-graphql`,
options: {
url: process.env.CRAFT_API_URL,
typeName: "Craft",
fieldName: "craft",
headers: {
Authorization: `bearer ${process.env.CRAFT_API_TOKEN}`,
},
},
},
// Get build date
{
resolve: `gatsby-plugin-build-date`,
options: {
formatAsDateString: false,
},
},
],
};
Help me to solve this problem.
In my case I was able to solve by adding the following configuration in package.json.
"resolutions": {
"sanitize.css": "12.0.1"
},
Finally, this problem has been solved.
Using yarn instead of using npm solved the problem.
Remove node_modules and yarn install
After that, the problem has gone away.
Thank you.

configuring base url nuxt for digital ocean deployement

i'm building ecommerce web app using nuxt and node.js/express. when i'm building locally i have no problem making axios api calls. base url is configured as the following
const baseDomain = 'http://localhost:8080/';
then all i do is
async getProducts({ commit }, payload) {
const reponse = await Repository.get(
`${baseUrl}/products?${serializeQuery(payload)}`
)
.then(response => {
commit('setProducts', response.data);
return response.data;
})
.catch(error => ({ error: JSON.stringify(error) }));
return reponse;
},
now the problem is when i move my whole app to digital ocean, i tried the following changes
const baseDomain = 'https://0.0.0.0:8080/';
my nuxt.js config
export default {
ssr: false,
head: {
titleTemplate: 'Lokazz',
title: 'Lokazz',
meta: [
{ charset: 'utf-8' },
{
name: 'viewport',
content: 'width=device-width, initial-scale=1'
},
{
hid: 'description',
name: 'description',
content:
'Lokazz'
}
],
link: [
{
rel: 'stylesheet',
href:
'https://fonts.googleapis.com/css?family=Work+Sans:300,400,500,600,700&amp;subset=latin-ext'
}
]
},
css: [
'swiper/dist/css/swiper.css',
'~/static/fonts/Linearicons/Font/demo-files/demo.css',
'~/static/fonts/font-awesome/css/font-awesome.css',
'~/static/css/bootstrap.min.css',
'~/assets/scss/style.scss'
],
plugins: [
{ src: '~plugins/vueliate.js', ssr: false },
{ src: '~/plugins/swiper-plugin.js', ssr: false },
{ src: '~/plugins/vue-notification.js', ssr: false },
{ src: '~/plugins/axios.js'},
{ src: '~/plugins/lazyLoad.js', ssr: false },
{ src: '~/plugins/mask.js', ssr: false },
{ src: '~/plugins/toastr.js', ssr: false },
],
buildModules: [
'#nuxtjs/vuetify',
'#nuxtjs/style-resources',
'cookie-universal-nuxt'
],
styleResources: {
scss: './assets/scss/env.scss'
},
modules: ['#nuxtjs/axios', 'nuxt-i18n','vue-sweetalert2/nuxt', '#nuxtjs/auth-next', "bootstrap-vue/nuxt"],
bootstrapVue: {
bootstrapCSS: false, // here you can disable automatic bootstrapCSS in case you are loading it yourself using sass
bootstrapVueCSS: false, // CSS that is specific to bootstrapVue components can also be disabled. That way you won't load css for modules that you don't use
},
i18n: {
locales: [
{ code: 'en', file: 'en.json' },
],
strategy: 'no_prefix',
fallbackLocale: 'en',
lazy: true,
defaultLocale: 'en',
langDir: 'lang/locales/'
},
router: {
linkActiveClass: '',
linkExactActiveClass: 'active',
},
server: {
port: 8080, // default: 3000
host: '0.0.0.0' // default: localhost
/// this one works fine , the digital ocean support team told me to do this.
},
auth: {
strategies: {
local: {
token: {
property: "token",
global: true,
},
redirect: {
"login": "/account/login",
"logout": "/",
"home": "/page/ajouter-produit",
"callback": false
},
endpoints: {
login: { url: "/login", method: "post" },
logout: false, // we don't have an endpoint for our logout in our API and we just remove the token from localstorage
user:false
}
}
}
},
};
package.json file
{
"name": "martfury_vue",
"version": "1.3.0",
"description": "Martfury - Multi-purpose Ecomerce template with vuejs",
"author": "nouthemes",
"private": true,
"scripts": {
"dev": "nuxt",
"build": "nuxt build",
"start": "nuxt start",
"generate": "nuxt generate"
},
"config": {
"nuxt": {
"host": "0.0.0.0",
"port": "8080"
}
},
}
server index.js config
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose')
const cors = require('cors');
const url = 'mongodb+srv://****************************' // this works fine i manage to pull data from the cluster without a problem
const jwt = require('jsonwebtoken')
mongoose.connect(url, {useNewUrlParser:true}).then(()=>{
const app = express();
// middlleware
app.use(express.json())
app.use(cors());
//products routes
const products = require('./product/product.router');
app.use('/', products)
//users routes
const users = require('./user/user.router');
app.use('/', users)
const port = process.env.PORT || 8080;
app.listen(port, () => console.log(`Server started on port ${port}`));
}).catch(error => console.log(error.reason));
const con = mongoose.connection
con.on('open', () => {
console.log('connected...')
})
here's my github repo and file structure. the server and api folder is lokazz_api.
I would recommend you use Environment variables for this.
Install dotenv in your project and then configure it in your nuxt.config.js file.
Create a .env file in your root directory, and then set a key-value pair like this:
VUE_APP_BASE_URL="<value>"
Note you need to prefix your keys with VUE_APP.
Your .env should look like this:
VUE_APP_BASE_URL="http://localhost:8080/"
You can modify your variable to this: const baseDomain = process.env.BASE_URL;
Remember to add the .env file in the .gitignore file.
On your digital ocean terminal, you can create a .env file using the touch .env command, and then use Vim or Nano to modify the file.
If your project runs fine with an .env file, it should work as good on production.
DO NOT commit .env but rather aim to your Digitalocean dashboard and look in the settings. You should see a place where you can input your pair and then proceed.
As shown here: https://docs.digitalocean.com/products/app-platform/how-to/use-environment-variables/#using-bindable-variables-within-environment-variables

AssertionError 'import' is reserved when writing tests for custom eslint rule

The custom eslint rule runs ok in our project, but I cannot figure out how to run tests for it. My guess is that I am running wrong version of ecmascript and I need to use babel or adjust something in eslintrc.json to make this work with the mocha scripts.
Getting error message:
AssertionError [ERR_ASSERTION]: A fatal parsing error occurred: Parsing error: The keyword 'import' is reserved
The test:
/**
* #fileoverview Prohibit import underscore to help tree
* #author Jason Hocker
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
var rule = require("../../../lib/rules/no-full-lodash-import"),
RuleTester = require("eslint").RuleTester;
//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------
var ruleTester = new RuleTester();
ruleTester.run("no-full-lodash-import", rule, {
valid: [
{code: "import os from \"os\";\nimport fs from \"fs\";" },
{code: "import { merge } from \"lodash-es\";"}
],
invalid: [
{
code: "import _ from 'lodash';",
errors: [{
message: "Fill me in.",
type: "Me too"
}]
}
]
});
One of the .jslintrc.json files I tried:
{
"env": {
"browser": true,
"es6": true,
"mocha": true // add mocha as true to your ".eslintrc. *" file
},
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
}
},
"rules": {
"semi": "error"
}
}
ESLint docs suggest that you can pass a configuration object to the RuleTester constructor.
In your case it should probably look like this:
var config = {
env: {
browser: true,
es6: true,
mocha: true, // add mocha as true to your ".eslintrc. *" file
},
parserOptions: {
ecmaVersion: 6,
sourceType: 'module',
ecmaFeatures: {
jsx: true,
},
},
}
var ruleTester = new RuleTester()

Resources