import express from 'express' ; import bodyParser from 'body-parser' ; import cookieParser from 'cookie-parser' ; import compress from 'compression' ; import logger from 'morgan' ; import favicon from 'serve-favicon' ; import helmet from 'helmet' ; import { port , authCookieName } from '@config' ; import featureConfig from '@config/feature.config' ; import sign from './sign' ; import AMP from './amp' ; import './sitemap' ; import render from './render' ; import cache from './cache' ; import log4js from './log4js' ; const app = express ( ) ; if ( featureConfig . logs ) log4js ( app ) ; app . use ( helmet ( ) ) ; if ( featureConfig . debug ) app . use ( logger ( 'dev' ) ) ; app . use ( bodyParser . json ( { limit : '20mb' } ) ) ; app . use ( bodyParser . urlencoded ( { limit : '20mb' , extended : true } ) ) ; app . use ( cookieParser ( ) ) ; app . use ( compress ( ) ) ; app . use ( favicon ( './public/favicon.png' ) ) ; app . use ( express . static ( './dist/client' ) ) ; app . use ( express . static ( './public' ) ) ; app . use ( function ( req , res , next ) { if ( ! req . cookies [ authCookieName ] ) { let _cache = cache . get ( req . originalUrl ) ; if ( _cache ) { res . send ( _cache ) ; return ; } } const start_at = Date . now ( ) ; const _send = res . send ; res . send = function ( ) { res . set ( 'X-Execution-Time' , String ( Date . now ( ) - start_at ) + ' ms' ) ; return _send . apply ( res , arguments ) ; } ; next ( ) ; } ) ; app . use ( '/sign' , sign ( ) ) ; app . use ( '/amp' , AMP ( ) ) ; app . get ( '*' , async function ( req , res ) { let { code , redirect , html , meta , reduxState , user } = await render ( req , res ) ; if ( req . path == '/' && req . _parsedOriginalUrl && req . _parsedOriginalUrl . search && req . _parsedOriginalUrl . search . indexOf ( '?appshell' ) != - 1 ) { res . render ( '../dist/server/app-shell.ejs' , { theme : user && user . theme == 2 ? 'dark-theme' : 'light-theme' } ) ; return ; } res . status ( code ) ; if ( redirect ) { res . redirect ( redirect ) ; } else { res . render ( '../dist/server/index.ejs' , { html , reduxState , meta , theme : user && user . theme == 2 ? 'dark-theme' : 'light-theme' } , function ( err , html ) { if ( ! req . cookies [ authCookieName ] ) { cache . set ( req . originalUrl , html ) ; } res . send ( html ) ; } ) ; } } ) ; app . listen ( port ) ; console . log ( 'server started on port ' + port ) ; if ( featureConfig . memoryUsage ) { let timer = function ( ) { setTimeout ( ( ) => { console . log ( process . memoryUsage ( ) . heapUsed / 1024 / 1204 ) ; timer ( ) ; } , 5000 ) ; } ; timer ( ) ; }