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

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?

Related

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!

Next.js production js bundle is not minified

If I generate production js bundle in my next.js project, it's not minified.
For example white characters are not removed.
package.json
{
"name": "web",
"version": "0.1.0",
"private": true,
"scripts": {
"web": "cross-env NODE_ENV=development node server.js",
"dev": "next",
"devServer": "node server.js",
"build": "next build",
"start": "next start"
},
"dependencies": {
"#zeit/next-css": "^1.0.1",
"apollo-boost": "^0.4.4",
"apollo-upload-client": "^11.0.0",
"body-parser": "^1.19.0",
"cross-env": "^6.0.3",
"express": "^4.17.1",
"graphql": "^14.5.8",
"intl": "^1.2.5",
"js-cookie": "^2.2.1",
"js-cookies": "^1.0.4",
"lodash.chunk": "^4.2.0",
"next": "9.1.2",
"next-cookies": "^2.0.3",
"next-with-apollo": "^4.3.0",
"optimize-css-assets-webpack-plugin": "^6.0.0",
"react": "16.11.0",
"react-apollo": "^3.1.3",
"react-dom": "16.11.0",
"react-image-lightbox": "^5.1.1",
"react-input-range": "^1.3.0",
"react-intl": "^3.6.1",
"react-modal": "^3.11.1",
"react-perfect-scrollbar": "^1.5.3",
"react-slick": "^0.25.2",
"slick-carousel": "^1.8.1"
},
"devDependencies": {
"babel-eslint": "^10.1.0",
"eslint": "^7.25.0",
"eslint-config-airbnb": "^18.2.1",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-jsx-a11y": "^6.4.1",
"eslint-plugin-react": "^7.23.2",
"eslint-plugin-react-hooks": "^4.2.0"
}
}
next.config.js
const withCSS = require("#zeit/next-css");
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
module.exports = withCSS({
webpack(config, options) {
config.optimization.minimizer = [];
config.optimization.minimizer.push(new OptimizeCSSAssetsPlugin({}));
return config;
},
distDir: "build",
});
server.js
const express = require('express');
const next = require('next');
const bodyParser = require("body-parser");
const dev = process.env.NODE_ENV !== undefined;
var app;
if(dev){
app = next({ dev});
}else{
app = next({ dev,conf:{
distDir: 'build'
} });
}
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = express();
server.use('/Public', express.static(__dirname + '/Public'));
server.use('/.well-known', express.static(__dirname + '/Public'));
server.use(bodyParser.urlencoded({ extended: false }));
server.use(bodyParser.json());
server.get('/', (req, res) => {
return app.render(req, res, '/index');
});
server.get('/robots.txt', (req, res) => {
return app.render(req, res, '/robots');
});
server.get('/sitemap.xml', (req, res) => {
return app.render(req, res, '/sitemap');
});
server.listen(8890, err => {
if (err) throw err
console.log('> Ready on http://localhost:8890')
})
})
If I run npm run build, dev variable in server.js is false.
The issue is on line:
config.optimization.minimizer = [];
Removing this line, minification works.

#react-native-firebase breaking unit tests

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"],

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