#react-native-firebase breaking unit tests - firebase

I installed v6 of #react-native-firebase, it's working as expected but when I try to run a unit test I get the following error:
Jest encountered an unexpected token
Details:
/node_modules/#react-native-firebase/database/lib/index.js:18
import { isBoolean, isNumber, isString } from '#react-native-firebase/app/lib/common';
^
SyntaxError: Unexpected token {
I tried adding #react-native-firebase/database & #react-native-firebase/app to jest config transformIgnorePatterns and get the following error:
Test suite failed to run
Invariant Violation: Native module cannot be null.
at invariant (node_modules/invariant/invariant.js:40:15)
at RNFBNativeEventEmitter.NativeEventEmitter (node_modules/react-native/Libraries/EventEmitter/NativeEventEmitter.js:36:7)
at new RNFBNativeEventEmitter (node_modules/#react-native-firebase/app/lib/internal/RNFBNativeEventEmitter.js:24:5)
at Object.<anonymous> (node_modules/#react-native-firebase/app/lib/internal/RNFBNativeEventEmitter.js:48:16)
at Object.<anonymous> (node_modules/#react-native-firebase/app/lib/internal/registry/nativeModule.js:21:1)
I also tried mocking the module with Jest like so:
import * as FBCommon from '#react-native-firebase/app/lib/common'
jest.mock(FBCommon, () => {
return () => ({
isBoolean: jest.fn(),
isNumber: jest.fn(),
isString: jest.fn()
})
});
and like this:
jest.mock('#react-native-firebase/database', () => {
return () => ({
ref: jest.fn()
})
});
but get the same error, any suggestions?
my package.json:
{
"name": "Project",
"version": "0.0.1",
"private": true,
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"start": "react-native start",
"test": "jest",
"lint": "eslint ."
},
"dependencies": {
"#react-native-community/push-notification-ios": "^1.0.6",
"#react-native-firebase/app": "^6.3.1",
"#react-native-firebase/database": "^6.3.1",
"#react-native-firebase/messaging": "^6.3.1",
"axios": "^0.19.0",
"base-64": "^0.1.0",
"blinkid-react-native": "^5.2.0",
"firebase": "^7.6.0",
"lodash": "^4.17.15",
"mobx": "^5.15.0",
"mobx-persist": "^0.4.1",
"mobx-react": "^6.1.4",
"react": "16.9.0",
"react-native": "0.61.4",
"react-native-auth0": "^2.1.0",
"react-native-collapsible": "^1.5.1",
"react-native-config": "^0.12.0",
"react-native-confirmation-code-input": "^1.0.4",
"react-native-datepicker": "^1.7.2",
"react-native-device-info": "^5.4.1",
"react-native-elements": "^1.2.7",
"react-native-freshchat-sdk": "^2.3.0",
"react-native-gesture-handler": "^1.5.2",
"react-native-in-app-notification": "^3.0.1",
"react-native-keyboard-aware-scroll-view": "^0.9.1",
"react-native-phone-input": "^0.2.4",
"react-native-picker-select": "^6.3.3",
"react-native-push-notification": "^3.1.9",
"react-native-reanimated": "^1.4.0",
"react-native-screens": "^1.0.0-alpha.23",
"react-native-signature-capture": "^0.4.10",
"react-native-vector-icons": "^6.6.0",
"react-native-webview": "^8.0.3",
"react-navigation": "^4.0.10",
"react-navigation-stack": "^1.10.3"
},
"devDependencies": {
"#babel/core": "^7.7.2",
"#babel/runtime": "^7.7.2",
"#react-native-community/eslint-config": "^0.0.5",
"babel-jest": "^24.9.0",
"babel-plugin-module-resolver": "^4.0.0",
"chai": "^4.1.2",
"chai-enzyme": "1.0.0-beta.0",
"enzyme": "^3.3.0",
"enzyme-adapter-react-16": "^1.1.1",
"eslint": "^6.6.0",
"jest": "^24.9.0",
"jsdom": "15.2.1",
"jsdom-global": "3.0.2",
"metro-react-native-babel-preset": "^0.57.0",
"react-dom": "^16.12.0",
"react-test-renderer": "16.9.0",
"sinon": "^7.2.2"
},
"jest": {
"preset": "react-native",
"setupFilesAfterEnv": [
"./setUpTests.js"
],
"transformIgnorePatterns": [
"node_modules/(?!((jest-)?react-native|#react-native-firebase/database|#react-native-firebase/app|react-clone-referenced-element|expo(nent)?|#expo(nent)?/.*|react-navigation|#react-navigation/.*|sentry-expo|native-base))"
]
}
}

You could mock firebase database by creating a mock module in a mocks directory like this:
mkdir -p __mocks__/#react-native-firebase/database
touch index.js
And use jest mocking functions in index.js for the firebase version and database functionalities to test. Something along these lines:
const database = {
functionality1: jest.fn(() => ({
propertyExample1: jest.fn(() => Promise.resolve(true)),
...
})),
...
functionality2: jest.fn(() => ({
property2: jest.fn(() => Promise.resolve(true)),...
})),
};
export default database;

This occurs because the native emitter isn't properly mocked by the library. Adding the following snippet at the top of your tests can resolve this by ensuring the module isn't null.
jest.mock('react-native/Libraries/EventEmitter/NativeEventEmitter');

I solved the issue creating jest.setup.js file with the content:
jest.mock('react-native/Libraries/EventEmitter/NativeEventEmitter');
And then in package.json inside jest
"setupFiles": ["./yourPath/jest.setup.js"],

Related

How to build next.js app with custom server for production

I have created a next.js app in there I have a custom server dir. I am using koa.js as my custom server. It works fine on development but, when I build the app, the api routes show 404 not found error. Below is my package.json
{
"name": "dogs",
"version": "0.1.0",
"private": true,
"engines": {
"node": ">=18.7.0",
"yarn": ">=1.22.17",
"npm": "please-use-yarn"
},
"scripts": {
"dev": "nodemon ./server/index.js",
"ngrok": "ngrok http 3000",
"build": "next build",
"start": "next start",
"lint": "next lint",
"prettier": "prettier --write .",
"prepare": "husky install",
"storybook": "start-storybook -p 6006",
"build-storybook": "build-storybook"
},
"dependencies": {
"#babel/polyfill": "^7.12.1",
"#babel/preset-env": "^7.20.2",
"#babel/register": "^7.18.9",
"#fireworks-js/preact": "^2.10.1",
"#koa/cors": "^4.0.0",
"#next/font": "13.1.1",
"#react-email/button": "^0.0.6",
"#react-email/container": "^0.0.7-canary.1",
"#react-email/head": "^0.0.4",
"#react-email/hr": "^0.0.4",
"#react-email/html": "^0.0.4",
"#react-email/img": "^0.0.4",
"#react-email/link": "^0.0.4",
"#react-email/preview": "^0.0.5",
"#react-email/render": "^0.0.6",
"#react-email/section": "^0.0.7-canary.1",
"#react-email/text": "^0.0.4",
"#sendgrid/mail": "^7.7.0",
"TagCloud": "^2.3.2",
"autoprefixer": "^10.4.13",
"aws-sdk": "^2.1300.0",
"babel-polyfill": "^6.26.0",
"bcryptjs": "^2.4.3",
"daisyui": "^2.47.0",
"dotenv": "^16.0.3",
"eslint": "8.30.0",
"eslint-config-next": "13.1.1",
"express": "^4.18.2",
"framer-motion": "^9.0.1",
"gsap": "^3.11.4",
"isomorphic-fetch": "^3.0.0",
"jsonwebtoken": "^9.0.0",
"koa": "^2.14.1",
"koa-body": "^6.0.1",
"koa-cache-control": "^2.0.0",
"koa-combine-routers": "^4.0.2",
"koa-conditional-get": "^3.0.0",
"koa-cookie": "^1.0.0",
"koa-etag": "^4.0.0",
"koa-mongo": "^1.9.3",
"koa-multer": "^1.0.2",
"koa-router": "^12.0.0",
"koa-session": "^6.2.0",
"koa-static": "^5.0.0",
"koa-static-cache": "^5.1.4",
"mongodb": "^4.13.0",
"mongoose": "^6.8.2",
"multer": "^1.4.5-lts.1",
"next": "13.1.1",
"postcss": "^8.4.20",
"primereact": "^8.7.3",
"react": "18.2.0",
"react-confetti": "^6.1.0",
"react-dom": "18.2.0",
"react-icons": "^4.7.1",
"react-multi-select-component": "^4.3.4",
"react-particles": "^2.8.0",
"react-select": "^5.7.0",
"react-tsparticles": "^2.8.0",
"split-type": "^0.3.3",
"tailwindcss": "^3.2.4",
"tsparticles": "^2.8.0",
"tsparticles-engine": "^2.8.0",
"tsparticles-preset-fireworks": "^2.8.0",
"winston": "^3.8.2"
},
"devDependencies": {
"#babel/core": "^7.20.7",
"#commitlint/cli": "^17.3.0",
"#commitlint/config-conventional": "^17.3.0",
"#storybook/addon-actions": "^6.5.15",
"#storybook/addon-essentials": "^6.5.15",
"#storybook/addon-interactions": "^6.5.15",
"#storybook/addon-links": "^6.5.15",
"#storybook/builder-webpack5": "^6.5.15",
"#storybook/manager-webpack5": "^6.5.15",
"#storybook/react": "^6.5.15",
"#storybook/testing-library": "^0.0.13",
"babel-loader": "^8.3.0",
"cross-env": "^7.0.3",
"husky": "^8.0.2",
"ngrok": "^4.3.3",
"nodemon": "^2.0.20",
"prettier": "^2.8.1"
},
"resolutions": {
"webpack": "^5"
}
}
Below is my server code
import '#babel/polyfill';
import dotenv from 'dotenv';
import 'isomorphic-fetch';
import next from 'next';
import Koa from 'koa';
import Router from 'koa-router';
import UserRouter from './routes/user';
import DataRouter from './routes/data';
import EmailRouter from './routes/emails';
import MongoClientConnection from './db';
import cookie from 'koa-cookie';
dotenv.config();
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const server = new Koa();
const router = new Router();
// Initialize NextJs instance and expose request handler
const app = next({ dev });
const handler = app.getRequestHandler();
(async () => {
try {
await app.prepare();
router.get('/custom-page', async (ctx) => {
await app.render(ctx.req, ctx.res, '/', ctx.query);
ctx.respond = false;
});
const db = await MongoClientConnection.Get();
server.context.db = db;
const handleRequest = async (ctx) => {
await handler(ctx.req, ctx.res);
ctx.respond = false;
ctx.res.statusCode = 200;
};
router.get('/_next/webpack-hmr', handleRequest); // Webpack content is clear
router.get('(.*)', async (ctx) => {
await handleRequest(ctx);
});
server.use(cookie());
server.use(UserRouter.routes()).use(UserRouter.allowedMethods());
server.use(DataRouter.routes()).use(DataRouter.allowedMethods());
server.use(EmailRouter.routes()).use(EmailRouter.allowedMethods());
server.use(router.routes());
server.listen(port, (_) => console.log(`App running on port ${port}`));
} catch (e) {
console.error(e);
process.exit();
}
})();
How can I build my next.js app so my api routes work on production?

Get refreshToken react-native firebase and #react-native-google-signin/google-signin

I need to get my accessToken and my refreshToken when I authenticate with fireabse. I have read a lot of the documentation and I can't understand how to get the refreshToken.
I get the accessToken from the GoogleSignIn.getTokens() method.
But I can't get the refreshToken from any method or function that these libraries provide me.
I need accessToken and refreshToken to send it to my backend. In other applications I am already receiving it, through other methods, but what would be the problem here? is the library wrong? I am not understanding the documentation? Why can't I really understand where to get it from or if the idToken updates itself or maybe the refreshToken is not sent anymore?
my code =>
import { GoogleSignin } from '#react-native-google-signin/google-signin';
import auth from '#react-native-firebase/auth';
GoogleSignin.configure({
webClientId:
'xxxxxxxxxxxxxxxxxxxxx',
});
const onGoogleButtonPress = async () => {
// Get the users ID token
const { idToken } = await GoogleSignin.signIn();
// Create a Google credential with the token
const googleCredential = auth.GoogleAuthProvider.credential(idToken);
// Sign-in the user with the credential
return auth().signInWithCredential(googleCredential);
};
export { onGoogleButtonPress };
React Native Info =>
react: 18.1.0 => 18.1.0
react-native: 0.70.6 => 0.70.6
Package.json ->
{
"name": "asset_management_mobile",
"version": "0.0.1",
"private": true,
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"start": "react-native start",
"test": "jest",
"lint": "eslint ."
},
"dependencies": {
"#invertase/react-native-apple-authentication": "^2.2.2",
"#react-native-firebase/app": "^15.4.0",
"#react-native-firebase/auth": "^15.4.0",
"#react-native-google-signin/google-signin": "^8.0.0",
"#react-native-masked-view/masked-view": "0.2.0",
"#react-navigation/bottom-tabs": "^6.5.2",
"#react-navigation/native": "^6.0.12",
"#react-navigation/stack": "^6.2.3",
"#types/react-native-background-timer": "^2.0.0",
"convert-string": "^0.1.0",
"depcheck": "^1.4.3",
"deprecated-react-native-prop-types": "^2.3.0",
"react": "18.1.0",
"react-native": "0.70.6",
"react-native-android-open-settings": "^1.3.0",
"react-native-background-timer": "^2.4.1",
"react-native-ble-manager": "^8.4.3",
"react-native-bluetooth-state-manager": "^1.3.4",
"react-native-gesture-handler": "^2.6.0",
"react-native-gradle-plugin": "^0.70.2",
"react-native-linear-gradient": "^2.6.2",
"react-native-permissions": "^3.6.1",
"react-native-reanimated": "^2.10.0",
"react-native-safe-area-context": "^4.3.3",
"react-native-screens": "^3.17.0",
"react-native-splash-screen": "^3.3.0",
"react-native-svg": "^13.1.0",
"react-native-swiper": "^1.6.0",
"react-native-vision-camera": "^2.15.2",
"vision-camera-code-scanner": "^0.2.0"
},
"devDependencies": {
"#babel/core": "^7.14.6",
"#babel/runtime": "^7.14.6",
"#react-native-community/eslint-config": "^3.0.0",
"#types/convert-string": "^0.1.1",
"#types/jest": "^29.0.0",
"#types/react": "^18.0.18",
"#types/react-native": "^0.69.6",
"#types/react-test-renderer": "^18.0.0",
"babel-jest": "^29.0.1",
"babel-plugin-module-resolver": "^4.1.0",
"eslint": "^8.23.0",
"jest": "^29.0.1",
"metro-react-native-babel-preset": "^0.72.1",
"react-native-svg-transformer": "^1.0.0",
"react-native-typescript-transformer": "^1.2.13",
"react-test-renderer": "^18.2.0",
"ts-jest": "^28.0.8",
"typescript": "^4.3.5"
},
"jest": {
"preset": "react-native",
"moduleFileExtensions": [
"ts",
"tsx",
"js"
],
"transform": {
"^.+\\.(js)$": "<rootDir>/node_modules/babel-jest",
"\\.(ts|tsx)$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
},
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
"testPathIgnorePatterns": [
"\\.snap$",
"<rootDir>/node_modules/"
],
"cacheDirectory": ".jest/cache"
}
}
I need your help!! Thanks!

Cannot find module 'firebase/app' while deploying Angular Universal app

I'm dealing with this issue for almost two weeks now. I tried a lot of workarounds but none seems to be working. I've installed angular-fire and firebase to its latest version, tried ng add #angular/fire, configured custom webpack.config.ts, tried rolling back to every suggested previous version. None fixed this issue.
The Actual Error:
de-10#de10-LIFEBOOK-A555:~/Desktop$ node dist/server.js
internal/modules/cjs/loader.js:797
throw err;
^
Error: Cannot find module 'firebase/app'
Require stack:
- /home/de-10/Desktop/dist/server.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:794:15)
at Function.Module._load (internal/modules/cjs/loader.js:687:27)
at Module.require (internal/modules/cjs/loader.js:849:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (/home/de-10/Desktop/dist/server.js:125276:18)
at __webpack_require__ (/home/de-10/Desktop/dist/server.js:20:30)
at Module.<anonymous> (/home/de-10/Desktop/dist/server.js:125199:70)
at __webpack_require__ (/home/de-10/Desktop/dist/server.js:20:30)
at Module.<anonymous> (/home/de-10/Desktop/dist/server.js:124984:78)
at __webpack_require__ (/home/de-10/Desktop/dist/server.js:20:30) {
code: 'MODULE_NOT_FOUND',
requireStack: [ '/home/de-10/Desktop/dist/server.js' ]
}
And I can't let go of Firebase cause then I face:
ERROR in ../node_modules/#angular/fire/auth/auth.d.ts:4:28 - error TS2307: Cannot find module 'firebase/app'.
4 import { User, auth } from 'firebase/app';
~~~~~~~~~~~~~~
../node_modules/#angular/fire/firebase.app.module.d.ts:2:74 - error TS2307: Cannot find module 'firebase/app'.
2 import { auth, database, messaging, storage, firestore, functions } from 'firebase/app';
~~~~~~~~~~~~~~
../node_modules/#angular/fire/firestore/collection-group/collection-group.d.ts:2:27 - error TS2307: Cannot find module 'firebase/app'.
~~~~~~~~~~~~~
.
.
.
app/services/notification.service.ts:29:38 - error TS2339: Property 'id' does not exist on type 'QueryDocumentSnapshot<unknown>'.
29 id: snap.payload.doc.id,
~~
app/services/notification.service.ts:68:35 - error TS2339: Property 'type' does not exist on type 'DocumentChange<unknown>'.
68 return snap.payload.type
~~~~
.
.
.
package.json
{
"name": "universal-ssr",
"version": "0.0.0",
"license": "MIT",
"scripts": {
"ng": "ng",
"start": "npm run build:ssr",
"staging": "npm run build:ssr-staging && npm run serve:ssr",
"production": "npm run build:ssr && npm run serve:ssr",
"prod": "npm run build:ssr-production && npm run serve:ssr",
"build": "ng build --prod",
"test": "ng test",
"dev-start": "ng serve",
"ng serve": "ng serve --aot",
"lint": "ng lint",
"e2e": "ng e2e",
"build:ssr": "npm run build:client-and-server-bundles && npm run webpack:server",
"build:ssr-staging": "npm run build:client-and-server-bundles-staging && npm run webpack:server",
"build:ssr-production": "npm run build:client-and-server-bundles-production && npm run webpack:server",
"serve:ssr": "node dist/server.js",
"build:client-and-server-bundles": "ng build --prod --build-optimizer && ng run universal-ssr:server --bundleDependencies all",
"build:client-and-server-bundles-staging": "ng build --c=staging --build-optimizer=true --stats-json && ng run universal-ssr:server",
"build:client-and-server-bundles-production": "ng build --c=production --build-optimizer=true && ng run universal-ssr:server --bundleDependencies all",
"webpack:server": "webpack --config webpack.config.js --progress --colors",
"webpack:analyzer": "webpack-bundle-analyzer dist/browser/stats.json",
"compodoc": "npx compodoc -p src/tsconfig.app.json -o"
},
"private": true,
"dependencies": {
"#angular/animations": "^8.2.14",
"#angular/cdk": "^5.2.5",
"#angular/common": "^8.2.14",
"#angular/compiler": "^8.2.14",
"#angular/core": "^8.2.14",
"#angular/fire": "^5.4.2",
"#angular/forms": "^8.2.14",
"#angular/material": "^5.2.5",
"#angular/platform-browser": "^8.2.14",
"#angular/platform-browser-dynamic": "^8.2.14",
"#angular/platform-server": "^8.2.14",
"#angular/pwa": "^0.803.24",
"#angular/router": "^8.2.14",
"#angular/service-worker": "^8.2.14",
"#ng-bootstrap/ng-bootstrap": "^4.0.0",
"#nguniversal/express-engine": "^6.1.0",
"#nguniversal/module-map-ngfactory-loader": "^6.1.0",
"angular2-datetimepicker": "^1.1.1",
"bootstrap": "^4.4.1",
"city-timezones": "^1.2.0",
"core-js": "^2.6.11",
"cors": "^2.8.4",
"express": "^4.17.1",
"firebase": "^7.13.1",
"jquery": "^3.4.1",
"moment-timezone": "^0.5.27",
"ng-bootstrap": "^1.6.3",
"ng2-search-filter": "^0.5.1",
"ngx-clipboard": "12.2.1",
"ngx-google-places-autocomplete": "^2.0.4",
"ngx-pagination": "^3.3.1",
"ngx-spinner": "^2.0.0",
"ngx-toggle-switch": "^2.0.5",
"ngx-ui-switch": "^8.3.0",
"rxjs": "^6.5.4",
"rxjs-compat": "^6.0.0",
"save": "^2.4.0",
"ts-loader": "^4.0.0",
"tslib": "^1.10.0",
"uuid": "^3.4.0",
"zone.js": "~0.9.1"
},
"devDependencies": {
"#angular-devkit/build-angular": "~0.803.23",
"#angular/cli": "^8.3.23",
"#angular/compiler-cli": "^8.2.14",
"#angular/http": "^7.2.16",
"#angular/language-service": "^8.2.14",
"#types/jasmine": "2.8.3",
"#types/jasminewd2": "^2.0.8",
"#types/node": "^6.14.9",
"codelyzer": "^5.0.1",
"jasmine-core": "~2.8.0",
"jasmine-spec-reporter": "~4.2.1",
"karma": "^4.4.1",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "^2.1.1",
"karma-jasmine": "~1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "5.4.2",
"ts-node": "~4.1.0",
"tslint": "~5.9.1",
"typescript": "~3.5.3",
"webpack-cli": "^3.1.0"
}
}
webpack.config.js:
// Work around for https://github.com/angular/angular-cli/issues/7200
const path = require('path');
const webpack = require('webpack');
// change the regex to include the packages you want to exclude
const regex = /firebase\/(app|firestore)/;
module.exports = {
mode: 'production',
entry: {
// This is our Express server for Dynamic universal
server: './server.ts'
},
externals: {
'./dist/server/main': 'require("./server/main")'
},
target: 'node',
node: {
__dirname: false,
__filename: false,
},
resolve: { extensions: ['.ts', '.js'] },
target: 'node',
mode: 'none',
// this makes sure we include node_modules and other 3rd party libraries
externals: [/node_modules/, function (context, request, callback) {
// exclude firebase products from being bundled, so they will be loaded using require() at runtime.
if (regex.test(request)) {
return callback(null, 'commonjs ' + request);
}
callback();
}],
optimization: {
minimize: false
},
output: {
// Puts the output at the root of the dist folder
path: path.join(__dirname, 'dist'),
filename: '[name].js'
},
module: {
noParse: /polyfills-.*\.js/,
rules: [
{ test: /\.ts$/, loader: 'ts-loader' },
{
// Mark files inside `#angular/core` as using SystemJS style dynamic imports.
// Removing this will cause deprecation warnings to appear.
test: /(\\|\/)#angular(\\|\/)core(\\|\/).+\.js$/,
parser: { system: true },
},
]
},
plugins: [
new webpack.ContextReplacementPlugin(
// fixes WARNING Critical dependency: the request of a dependency is an expression
/(.+)?angular(\\|\/)core(.+)?/,
path.join(__dirname, 'src'), // location of your src
{} // a map of your routes
),
new webpack.ContextReplacementPlugin(
// fixes WARNING Critical dependency: the request of a dependency is an expression
/(.+)?express(\\|\/)(.+)?/,
path.join(__dirname, 'src'),
{}
)
]
};
server.ts:
import 'zone.js/dist/zone-node';
import * as express from 'express';
/* const express = require('express');
const join = require('path'); */
const compression = require('compression')
import { join } from 'path';
// Express server
const app = express();
// gzip
app.use(compression())
const PORT = process.env.PORT || 4000;
const DIST_FOLDER = join(__dirname, 'browser');/* 'dist/browser' */
// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const { AppServerModuleNgFactory, LAZY_MODULE_MAP, ngExpressEngine, provideModuleMap } = require('./dist/server/main');
// Our Universal express-engine (found # https://github.com/angular/universal/tree/master/modules/express-engine)
app.engine('html', ngExpressEngine({
bootstrap: AppServerModuleNgFactory,
providers: [
provideModuleMap(LAZY_MODULE_MAP)
]
}));
app.set('view engine', 'html');
app.set('views', DIST_FOLDER);
// Serve static files from /browser
app.get('*.*', express.static(DIST_FOLDER, {
maxAge: '1y'
}));
// All regular routes use the Universal engine
app.get('*', (req, res) => {
res.render('index', { req });
});
// Start up the Node server
app.listen(PORT, () => {
console.log(`Node Express server listening on http://localhost:${PORT}`);
});
You're getting this error because you're excluding firebase dependencies with this =>
const regex = /firebase\/(app|firestore)/;
module.exports = {
// this makes sure we include node_modules and other 3rd party libraries
externals: [/node_modules/, function (context, request, callback) {
// exclude firebase products from being bundled, so they will be loaded using require() at runtime.
if (regex.test(request)) {
return callback(null, 'commonjs ' + request);
}
callback();
}],
};
Remove this
if (regex.test(request)) {
return callback(null, 'commonjs ' + request);
}
and your app will be fine.
One workaround is to install npm packages (firebase and #angular/fire) beside the dist folder and then run the deployment script.

firebase.auth() hangs when chrome debugging is on

Using the same credentials the login login action hangs at firebase.auth() when chrome debug is on. It hangs until I tap on the screen. Only then the login proceeds.
As soon as I turn chrome debug off, the login action incl. firebase.auth() runs as fast as expected.
here is my package.json an the affected action:
Action:
export const loginUser = ({ email, password }) => (dispatch) => {
dispatch({ type: LOGIN_USER });
return firebase
.auth()
.signInWithEmailAndPassword(email, password)
.then((user) => {
setTimeout(() => null, 0);
dispatch(() => saveCredentials(email, password))
.then(dispatch(loginUserSuccess(user)))
.then(dispatch(weekplanFetch()))
.then(dispatch(recipeLibraryFetch()))
.then(() => {
NavigationService.navigate('Home');
});
})
.catch((error) => {
console.log(`sign in fail ${error}`);
return firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then((user) => {
dispatch(() => saveCredentials(email, password))
.then(dispatch(loginUserSuccess(user)))
.then(dispatch(initWeekplan()))
.then(dispatch(initRecipeLibrary()))
.then(() => {
NavigationService.navigate('Home');
});
})
.catch((userCreateFail) => {
// console.log(`user create fail ${userCreateFail}`);
dispatch(loginUserFail(userCreateFail.message));
});
});
};
package.json
{
"name": "WhatsForDinner",
"version": "1.0.5",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest",
"ios:beta": "(cd ios/ && bundle exec fastlane beta)",
"ios:commit": "cd ios/ && bundle exec fastlane commit",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"prettier": "prettier --write '*.js'",
"format-code": "yarn run prettier && yarn run lint:fix",
"precommit": "lint-staged",
"test:coverage": "jest --coverage && open coverage/lcov-report/index.html"
},
"lint-staged": {
"*.js": [
"yarn run format-code",
"git add",
"jest --bail --findRelatedTests --coverage"
]
},
"dependencies": {
"firebase": "^5.8.6",
"prop-types": "^15.6.0",
"react": "16.6.3",
"react-native": "0.57.8",
"react-native-code-push": "^5.5.2",
"react-native-image-picker": "^0.28.0",
"react-native-keychain": "^3.0.0",
"react-native-paper": "^1.12.0",
"react-native-vector-icons": "^6.4.1",
"react-navigation": "^1.6.1",
"react-redux": "^5.0.7",
"redux": "^3.7.2",
"redux-logger": "^3.0.6",
"redux-thunk": "^2.3.0",
"yarn": "^1.9.4"
},
"devDependencies": {
"babel-eslint": "^8.2.2",
"babel-jest": "^23.4.2",
"babel-preset-react-native": "^5",
"enzyme": "^3.7.0",
"enzyme-adapter-react-16": "^1.6.0",
"eslint": "^4.18.1",
"eslint-config-airbnb": "^16.1.0",
"eslint-plugin-import": "^2.7.0",
"eslint-plugin-jsx-a11y": "^6.0.3",
"eslint-plugin-react": "^7.12.3",
"husky": "^0.14.3",
"jest": "22.4.2",
"jest-fetch-mock": "^2.1.0",
"lint-staged": "^7.2.2",
"prettier": "1.10.2",
"react-dom": "^16.7.0",
"react-test-renderer": "16.4.1",
"redux-mock-store": "^1.5.3"
},
"jest": {
"preset": "react-native",
"setupFiles": [
"<rootDir>/tests/setup.js"
],
"transform": {
"^.+\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js"
},
"collectCoverageFrom": [
"app/**/*.js",
"!app/components/index.js"
],
"transformIgnorePatterns": [
"node_modules/(?!(jest-)?react-native|react-navigation)"
]
}
}

Change DATE_TIME_FORMAT const in JHipster + Angular2+ project

I am currently working on a Angular2+/Typescript/Bootstrap project generated with JHipster in which I have an entity "CalendarEvent" that has a startTime field of Java type Instant.
Today this field looks like this :
My problem is that I cannot know if that time is am or pm.
For instance, when I tried :
const startMoment = moment(this.startTime, DATE_TIME_FORMAT);
startMoment.set({hour: 18});
this.startTime= moment(startMoment).format(DATE_TIME_FORMAT);
in order to force the startTime hour to 18h (6pm), the form field showed 06:49. I therefore have no way to know if a time is in the morning or in the afternoon.
Now JHipster generated the entity creation/update form, in which the html code of this field is :
<label class="form-control-label" jhiTranslate="myApp.calendarEvent.startTime" for="field_startTime">Start Time</label>
<div class="d-flex">
<input id="field_startTime" type="datetime-local" class="form-control" name="startTime" max="endTime" [(ngModel)]="startTime" required/>
</div>
and the Typescript code (from which I removed few unrelated code):
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute } from '#angular/router';
import { HttpResponse, HttpErrorResponse } from '#angular/common/http';
import { Observable } from 'rxjs';
import * as moment from 'moment';
import { DATE_TIME_FORMAT } from 'app/shared/constants/input.constants';
import { JhiAlertService } from 'ng-jhipster';
import { ICalendarEvent } from 'app/shared/model/calendar-event.model';
import { CalendarEventService } from './calendar-event.service';
#Component({
selector: 'jhi-calendar-event-update',
templateUrl: './calendar-event-update.component.html'
})
export class CalendarEventUpdateComponent implements OnInit {
private _calendarEvent: ICalendarEvent;
isSaving: boolean;
startTime: string;
constructor(
private jhiAlertService: JhiAlertService,
private calendarEventService: CalendarEventService,
private activatedRoute: ActivatedRoute
) {}
ngOnInit() {
this.isSaving = false;
this.activatedRoute.data.subscribe(({ calendarEvent }) => {
this.calendarEvent = calendarEvent;
});
}
previousState() {
window.history.back();
}
save() {
this.isSaving = true;
this.calendarEvent.startTime = moment(this.startTime, DATE_TIME_FORMAT);
if (this.calendarEvent.id !== undefined) {
this.subscribeToSaveResponse(this.calendarEventService.update(this.calendarEvent));
} else {
this.subscribeToSaveResponse(this.calendarEventService.create(this.calendarEvent));
}
}
private subscribeToSaveResponse(result: Observable<HttpResponse<ICalendarEvent>>) {
result.subscribe((res: HttpResponse<ICalendarEvent>) => this.onSaveSuccess(), (res: HttpErrorResponse) => this.onSaveError());
}
private onSaveSuccess() {
this.isSaving = false;
this.previousState();
}
private onSaveError() {
this.isSaving = false;
}
private onError(errorMessage: string) {
this.jhiAlertService.error(errorMessage, null, null);
}
getSelected(selectedVals: Array<any>, option: any) {
if (selectedVals) {
for (let i = 0; i < selectedVals.length; i++) {
if (option.id === selectedVals[i].id) {
return selectedVals[i];
}
}
}
return option;
}
get calendarEvent() {
return this._calendarEvent;
}
set calendarEvent(calendarEvent: ICalendarEvent) {
this._calendarEvent = calendarEvent;
this.startTime = moment(calendarEvent.startTime).format(DATE_TIME_FORMAT);
}
}
Now you can see that the component has a startTime string attribute instanciated like this :
this.startTime = moment(calendarEvent.startTime).format(DATE_TIME_FORMAT);
(with calendarEvent.startTime of type Instant). Now in a config file, I saw :
export const DATE_TIME_FORMAT = 'YYYY-MM-DDThh:mm';
I thought that by changing the value of DATE_TIME_FORMAT to something like LLLL (found on Moment.js documentation) I would easily get a clearer format, but unfortunately, not only it does not change the form format, but it also appears uninitialized by default :
I also join my package.json and .yo-rc.json that are often asked to people requesting support (if any help) :
package.json
{
"name": "platform-overview-2",
"version": "0.0.0",
"description": "Description for platformOverview2",
"private": true,
"license": "UNLICENSED",
"cacheDirectories": [
"node_modules"
],
"dependencies": {
"#angular/common": "6.0.0",
"#angular/compiler": "6.0.0",
"#angular/core": "6.0.0",
"#angular/forms": "6.0.0",
"#angular/platform-browser": "6.0.0",
"#angular/platform-browser-dynamic": "6.0.0",
"#angular/router": "6.0.0",
"#fortawesome/angular-fontawesome": "0.1.0-9",
"#fortawesome/fontawesome-svg-core": "1.2.0-11",
"#fortawesome/free-solid-svg-icons": "5.1.0-8",
"#ng-bootstrap/ng-bootstrap": "2.0.0",
"bootstrap": "4.0.0",
"core-js": "2.5.3",
"jquery": "3.3.1",
"moment": "2.21.0",
"ng-jhipster": "0.5.4",
"ngx-cookie": "2.0.1",
"ngx-infinite-scroll": "0.5.1",
"ngx-webstorage": "2.0.1",
"reflect-metadata": "0.1.12",
"rxjs": "6.1.0",
"rxjs-compat": "6.1.0",
"swagger-ui": "2.2.10",
"tslib": "1.9.0",
"zone.js": "0.8.26"
},
"devDependencies": {
"#angular/cli": "^6.1.1",
"#angular/compiler-cli": "6.0.0",
"#ngtools/webpack": "6.0.0",
"#types/jest": "22.2.3",
"#types/node": "9.4.7",
"angular-router-loader": "0.8.2",
"angular2-template-loader": "0.6.2",
"browser-sync": "2.24.4",
"browser-sync-webpack-plugin": "2.2.2",
"cache-loader": "1.2.2",
"codelyzer": "4.2.1",
"copy-webpack-plugin": "4.5.1",
"css-loader": "0.28.10",
"exports-loader": "0.7.0",
"extract-text-webpack-plugin": "4.0.0-beta.0",
"file-loader": "1.1.11",
"fork-ts-checker-webpack-plugin": "0.4.1",
"friendly-errors-webpack-plugin": "1.7.0",
"generator-jhipster": "5.1.0",
"html-loader": "0.5.5",
"html-webpack-plugin": "3.2.0",
"husky": "0.14.3",
"jest": "22.4.3",
"jest-junit": "5.1.0",
"jest-preset-angular": "5.2.2",
"jest-sonar-reporter": "2.0.0",
"lint-staged": "7.0.0",
"merge-jsons-webpack-plugin": "1.0.14",
"moment-locales-webpack-plugin": "1.0.5",
"prettier": "1.11.1",
"proxy-middleware": "0.15.0",
"raw-loader": "0.5.1",
"rimraf": "2.6.1",
"simple-progress-webpack-plugin": "1.1.2",
"style-loader": "0.20.3",
"tapable": "1.0.0",
"thread-loader": "1.1.5",
"to-string-loader": "1.1.5",
"ts-loader": "4.0.1",
"tslint": "5.9.1",
"tslint-config-prettier": "1.9.0",
"tslint-loader": "3.6.0",
"typescript": "2.7.2",
"uglifyjs-webpack-plugin": "1.2.5",
"webpack": "4.8.0",
"webpack-cli": "2.1.3",
"webpack-dev-server": "3.1.4",
"webpack-merge": "4.1.2",
"webpack-notifier": "1.6.0",
"webpack-visualizer-plugin": "0.1.11",
"workbox-webpack-plugin": "3.2.0",
"write-file-webpack-plugin": "4.2.0",
"xml2js": "0.4.19"
},
"engines": {
"node": ">=8.9.0",
"yarn": ">=1.3.2"
},
"lint-staged": {
"src/**/*.{ts,css,scss}": [
"prettier --write",
"git add"
]
},
"scripts": {
"precommit": "lint-staged",
"prettier:format": "yarn prettier --write 'src/**/*.{ts,css,scss}'",
"lint": "tslint --project tsconfig.json -e 'node_modules/**'",
"lint:fix": "yarn run lint --fix",
"ngc": "ngc -p tsconfig-aot.json",
"cleanup": "rimraf target/{aot,www}",
"clean-www": "rimraf target//www/app/{src,target/}",
"start": "yarn run webpack:dev",
"serve": "yarn run start",
"build": "yarn run webpack:prod",
"test": "yarn run lint && jest --coverage --logHeapUsage -w=2 --config src/test/javascript/jest.conf.js",
"test:watch": "yarn test --watch --clearCache",
"webpack:dev": "yarn run webpack-dev-server --config webpack/webpack.dev.js --inline --hot --port=9060 --watch-content-base --env.stats=minimal",
"webpack:dev-verbose": "yarn run webpack-dev-server --config webpack/webpack.dev.js --inline --hot --port=9060 --watch-content-base --profile --progress --env.stats=normal",
"webpack:build:main": "yarn run webpack --config webpack/webpack.dev.js --env.stats=normal",
"webpack:build": "yarn run cleanup && yarn run webpack:build:main",
"webpack:prod:main": "yarn run webpack --config webpack/webpack.prod.js --profile",
"webpack:prod": "yarn run cleanup && yarn run webpack:prod:main && yarn run clean-www",
"webpack:test": "yarn run test",
"webpack-dev-server": "node --max_old_space_size=4096 node_modules/webpack-dev-server/bin/webpack-dev-server.js",
"webpack": "node --max_old_space_size=4096 node_modules/webpack/bin/webpack.js"
},
"jestSonar": {
"reportPath": "target/test-results/jest",
"reportFile": "TESTS-results-sonar.xml"
}
}
.yo-rc.json
{
"generator-jhipster": {
"promptValues": {
"packageName": "com.worldline.app",
"nativeLanguage": "en"
},
"jhipsterVersion": "5.1.0",
"applicationType": "monolith",
"baseName": "platformOverview2",
"packageName": "com.worldline.app",
"packageFolder": "com/worldline/app",
"serverPort": "8080",
"authenticationType": "jwt",
"cacheProvider": "ehcache",
"enableHibernateCache": true,
"websocket": false,
"databaseType": "sql",
"devDatabaseType": "h2Disk",
"prodDatabaseType": "mysql",
"searchEngine": false,
"messageBroker": false,
"serviceDiscoveryType": false,
"buildTool": "maven",
"enableSocialSignIn": false,
"enableSwaggerCodegen": false,
"jwtSecretKey": "455e1315207269bf7ba9685bdba93b4ff0224ba0",
"clientFramework": "angularX",
"useSass": false,
"clientPackageManager": "yarn",
"testFrameworks": [],
"jhiPrefix": "jhi",
"enableTranslation": true,
"nativeLanguage": "en",
"languages": [
"en",
"fr",
"de",
"es",
"ro",
"zh-cn",
"pl"
]
}
}
Please let me know if you need more information.
Thanks in advance for any help you can provide :) !

Resources