Skip to content

Commit

Permalink
feat: add support for standalone mode (default in development) (#70)
Browse files Browse the repository at this point in the history
* feat: add support for standalone mode (default in development)

* feat: allow cli overrides, print build parameters

* chore: update log format
  • Loading branch information
amcgee committed Sep 30, 2019
1 parent fa7cb69 commit 485b6da
Show file tree
Hide file tree
Showing 9 changed files with 74 additions and 58 deletions.
41 changes: 30 additions & 11 deletions cli/src/commands/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,19 +27,31 @@ const getNodeEnv = () => {
return null
}

// This is nasty and frankly wrong (also don't use long unweildy capitalized names in a URL!) but has to match the current DHIS2 app server
// From https://github.com/dhis2/dhis2-core/blob/master/dhis-2/dhis-api/src/main/java/org/hisp/dhis/appmanager/App.java#L360-L371
const getUrlFriendlyName = name =>
name
.trim()
.replace(/[^A-Za-z0-9\s-]/g, '')
.replace(/ /g, '-')
const printBuildParam = (key, value) => {
reporter.print(chalk.green(` - ${key} =`), chalk.yellow(value))
}
const setAppParameters = (standalone, config) => {
process.env.PUBLIC_URL = process.env.PUBLIC_URL || '.'
printBuildParam('PUBLIC_URL', process.env.PUBLIC_URL)

if (
standalone === false ||
(typeof standalone === 'undefined' && !config.standalone)
) {
process.env.DHIS2_BASE_URL =
process.env.DHIS2_BASE_URL || config.coreApp ? `..` : `../../..`
printBuildParam('DHIS2_BASE_URL', process.env.DHIS2_BASE_URL)
} else {
printBuildParam('DHIS2_BASE_URL', '<standalone>')
}
}

const handler = async ({
cwd,
mode,
dev,
watch,
standalone,
shell: shellSource,
force,
}) => {
Expand All @@ -48,13 +60,14 @@ const handler = async ({
mode = mode || (dev && 'development') || getNodeEnv() || 'production'
loadEnvFiles(paths, mode)

reporter.info(`Build mode: ${chalk.bold(mode)}`)
printBuildParam('Build Mode', mode)

const config = parseConfig(paths)
const shell = makeShell({ config, paths })

process.env.PUBLIC_URL =
process.env.PUBLIC_URL ||
`/api/apps/${getUrlFriendlyName(config.title)}`
if (config.type === 'app') {
setAppParameters(standalone, config)
}

await fs.remove(paths.buildOutput)

Expand Down Expand Up @@ -139,6 +152,12 @@ const command = {
description: 'Watch source files for changes',
default: false,
},
standalone: {
type: 'boolean',
description:
'Build in standalone mode (overrides the d2.config.js setting)',
default: undefined,
},
},
handler,
}
Expand Down
25 changes: 0 additions & 25 deletions cli/src/lib/shell/env.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,30 +23,6 @@ const prefixEnvForCRA = env =>
{}
)

const getDHISConfig = () => {
const dhisConfigPath =
process.env.DHIS2_HOME && `${process.env.DHIS2_HOME}/config`

let dhisConfig
try {
dhisConfig = require(dhisConfigPath)
} catch (e) {
// Failed to load config file - use default config
reporter.debug(`\nWARNING! Failed to load DHIS config:`, e.message)
dhisConfig = {
baseUrl: 'http:https://localhost:8080',
authorization: 'Basic YWRtaW46ZGlzdHJpY3Q=', // admin:district
}
}

return dhisConfig
}

const envFromDHISConfig = config => ({
DHIS2_BASE_URL: config.baseUrl,
DHIS2_AUTHORIZATION: config.authorization,
})

const makeShellEnv = vars =>
Object.entries(vars).reduce(
(out, [key, value]) => ({
Expand All @@ -59,7 +35,6 @@ const makeShellEnv = vars =>
module.exports = vars => {
const env = {
...prefixEnvForCRA({
...envFromDHISConfig(getDHISConfig()),
...filterEnv(),
...makeShellEnv(vars),
}),
Expand Down
2 changes: 1 addition & 1 deletion docs/scripts/start.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# d2 app scripts start

Run a live-reloading development server on `localhost:3000`
Run a live-reloading development server on localhost

> **NOTE**: This command is currently unsupported for libraries
Expand Down
2 changes: 2 additions & 0 deletions examples/simple-app/d2.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ const config = {
title: 'Simple Example App',
description: 'This is a simple example application',

standalone: true, // Don't bake-in a DHIS2 base URL, allow the user to choose

entryPoints: {
app: './src/App',
},
Expand Down
2 changes: 1 addition & 1 deletion examples/simple-app/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -923,7 +923,7 @@
integrity sha512-+Rmw+QshbgiBielN7UH4VXfEeSnSj1N3d4HGqf3iekyUXCNdpZX2bD9QrH43KvdfH+lDp71Uh7y3FKEhzSbRLA==

"@dhis2/cli-app-scripts@file:../../cli":
version "1.4.2"
version "1.4.3"
dependencies:
"@babel/core" "^7.6.0"
"@babel/plugin-proposal-class-properties" "^7.4.4"
Expand Down
9 changes: 6 additions & 3 deletions shell/adapter/i18n/en.pot
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,15 @@ msgstr ""
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1)\n"
"POT-Creation-Date: 2019-06-18T09:28:13.445Z\n"
"PO-Revision-Date: 2019-06-18T09:28:13.445Z\n"
"POT-Creation-Date: 2019-09-26T16:40:43.483Z\n"
"PO-Revision-Date: 2019-09-26T16:40:43.483Z\n"

msgid "Please sign in"
msgstr ""

msgid "Server"
msgstr ""

msgid "Username"
msgstr ""

Expand All @@ -20,7 +23,7 @@ msgstr ""
msgid "Sign in"
msgstr ""

msgid "An error occurred in the DHIS2 Maps application."
msgid "An error occurred in the DHIS2 application."
msgstr ""

msgid "Something went wrong"
Expand Down
41 changes: 30 additions & 11 deletions shell/adapter/src/AuthBoundary/LoginModal.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@ import React, { useState } from 'react'
import i18n from '../locales'
import { Modal, Button, InputField } from '@dhis2/ui-core'

const staticUrl = process.env.REACT_APP_DHIS2_BASE_URL

export const LoginModal = ({ url }) => {
const [server, setServer] = useState(
staticUrl || window.localStorage.DHIS2_BASE_URL || ''
)
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [isDirty, setIsDirty] = useState(false)
Expand All @@ -12,18 +17,22 @@ export const LoginModal = ({ url }) => {
const onSubmit = async e => {
e.preventDefault()
setIsDirty(true)
if (isValid(username) && isValid(password)) {
if (isValid(server) && isValid(username) && isValid(password)) {
window.localStorage.DHIS2_BASE_URL = server
try {
await fetch(`${url}/dhis-web-commons-security/login.action`, {
method: 'POST',
credentials: 'include',
body: `j_username=${username}&j_password=${password}`,
headers: {
'X-Requested-With': 'XMLHttpRequest',
Accept: 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
},
})
await fetch(
`${server}/dhis-web-commons-security/login.action`,
{
method: 'POST',
credentials: 'include',
body: `j_username=${username}&j_password=${password}`,
headers: {
'X-Requested-With': 'XMLHttpRequest',
Accept: 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
},
}
)
} catch (e) {
console.log(
'TODO: This will always error and cancel the request until we get a real login endpoint!'
Expand All @@ -40,6 +49,16 @@ export const LoginModal = ({ url }) => {
<form onSubmit={onSubmit}>
<Modal.Title>{i18n.t('Please sign in')}</Modal.Title>
<Modal.Content>
{!staticUrl && (
<InputField
error={isDirty && !isValid(server)}
label={i18n.t('Server')}
name="server"
type="text"
value={server}
onChange={_ref => setServer(_ref.target.value)}
/>
)}
<InputField
error={isDirty && !isValid(username)}
label={i18n.t('Username')}
Expand Down
6 changes: 1 addition & 5 deletions shell/adapter/src/AuthBoundary/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,7 @@ export const AuthBoundary = ({ url, children }) => {
}

if (error) {
if (error.type === 'access') {
return <LoginModal url={url} />
}
console.log(JSON.stringify(error, undefined, 2))
throw error
return <LoginModal url={url} />
}

i18n.changeLanguage(data.userSettings.keyUiLocale)
Expand Down
4 changes: 3 additions & 1 deletion shell/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ const D2App = React.lazy(() =>
) // Automatic bundle splitting!

const appConfig = {
url: process.env.REACT_APP_DHIS2_BASE_URL || 'http:https://localhost:8080',
url:
process.env.REACT_APP_DHIS2_BASE_URL ||
window.localStorage.DHIS2_BASE_URL,
appName: process.env.REACT_APP_DHIS2_APP_NAME || '',
apiVersion: parseInt(process.env.REACT_APP_DHIS2_API_VERSION) || 32,
}
Expand Down

0 comments on commit 485b6da

Please sign in to comment.