Skip to content

Commit

Permalink
add minimal example for shared interface code
Browse files Browse the repository at this point in the history
  • Loading branch information
Jonas Verhoelen committed May 5, 2019
1 parent 4aae6be commit 4bb8f97
Show file tree
Hide file tree
Showing 5 changed files with 31 additions and 3 deletions.
3 changes: 3 additions & 0 deletions resources/views/index.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
</head>
<body>
<div id="app"></div>
<script type="text/javascript">
window.config = <%- JSON.stringify(config) %>
</script>
<script type="text/javascript" src="/static/app-bundle.js" async></script>
</body>
</html>
5 changes: 4 additions & 1 deletion service/frontend/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
console.log('index.ts')
const welcomePhrases = window.config.welcomePhrases

const app: HTMLElement = document.getElementById('app')!
app.innerHTML = welcomePhrases.map(phrase => `<h2>${phrase}</h2>`).join('')
11 changes: 9 additions & 2 deletions service/server/ExpressServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { CatEndpoints } from './cats/CatEndpoints'
import { RequestServices } from './types/CustomRequest'
import { addServicesToRequest } from './middlewares/ServiceDependenciesMiddleware'
import { Environment } from './Environment'
import { FrontendContext } from '../shared/FrontendContext'

/**
* Abstraction around the raw Express.js server and Nodes' HTTP server.
Expand Down Expand Up @@ -76,8 +77,14 @@ export class ExpressServer {
this.prepareAssets()
this.configureStaticAssets(server)

const renderPage = (template: string) => async (req: Request, res: Response, next: NextFunction) => {
res.type('text/html').render(template, { cssFiles: this.cssFiles })
const context: FrontendContext = {
cssFiles: this.cssFiles,
config: {
welcomePhrases: [ 'Bienvenue', 'Welcome', 'Willkommen', 'Welkom', 'Hoş geldin', 'Benvenuta', 'Bienvenido' ]
}
}
const renderPage = (template: string) => async (req: Request, res: Response, _: NextFunction) => {
res.type('text/html').render(template, context)
}

server.get('/', noCache, renderPage('index'))
Expand Down
8 changes: 8 additions & 0 deletions service/shared/FrontendContext.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export interface FrontendConfig {
welcomePhrases: string[]
}

export interface FrontendContext {
cssFiles?: string[]
config: FrontendConfig
}
7 changes: 7 additions & 0 deletions service/shared/Window.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { FrontendConfig } from './FrontendContext'

declare global {
interface Window {
config: FrontendConfig
}
}

0 comments on commit 4bb8f97

Please sign in to comment.