setup and run prettier

This commit is contained in:
Linus Miller 2020-08-27 21:41:56 +02:00
parent c4bb4c9c02
commit 3a3072681d
35 changed files with 464 additions and 384 deletions

2
.eslintignore Normal file
View File

@ -0,0 +1,2 @@
/build
/dump

22
.eslintrc Normal file
View File

@ -0,0 +1,22 @@
{
"root": true,
"settings": {
"import/resolver": {
"node": {
"extensions": [".js", ".jsx", ".mjs"]
}
}
},
"extends": ["standard", "prettier"],
"rules": {
"import/no-extraneous-dependencies": 2,
"no-console": [2, { "allow": ["info", "error", "warn"] }],
"no-unused-expressions": 0,
"no-unused-vars": 0,
"no-var": 2,
"prefer-const": 2
}
}

View File

@ -20,6 +20,6 @@ div.item.gu-mirror {
.gu-transit {
display: none !important;
opacity: 0.2;
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=20)";
-ms-filter: 'progid:DXImageTransform.Microsoft.Alpha(Opacity=20)';
filter: alpha(opacity=20);
}

View File

@ -1,4 +1,4 @@
@import "./dragula";
@import './dragula';
div.container {
width: 100%;

7
client/.eslintrc Normal file
View File

@ -0,0 +1,7 @@
{
"extends": ["../.eslintrc", "standard-jsx", "prettier/react"],
"env": {
"browser": true
}
}

View File

@ -1,51 +1,52 @@
import { pick } from 'lowline';
import { pick } from 'lowline'
export const DELETE_RESULT = 'DELETE_RESULT';
export const DELETE_RESULT = 'DELETE_RESULT'
const baseUrl = '/api/results';
const baseUrl = '/api/results'
const headers = {
'X-Requested-With': 'XMLHttpRequest',
accept: 'application/json',
};
}
export const FETCH_RESULTS = 'FETCH_RESULTS';
export const FETCH_RESULTS = 'FETCH_RESULTS'
// query can be a query string (without ?, ie not a search string)
export function fetchResults(query = {}) {
query = typeof query === 'string' ? query : qs.stringify(query);
query = typeof query === 'string' ? query : qs.stringify(query)
return (dispatch) => {
fetch(`${baseUrl}${query ? `?${query}` : ''}`, {
credentials: 'same-origin',
headers,
}).then((res) => res.json())
})
.then((res) => res.json())
.then((json) => {
const actions = [receiveResults(json.results || [])];
const actions = [receiveResults(json.results || [])]
if (json.perPage) {
actions.push(setPagination(pick(json, 'perPage', 'totalCount')));
actions.push(setPagination(pick(json, 'perPage', 'totalCount')))
}
dispatch(batchActions(actions));
});
};
dispatch(batchActions(actions))
})
}
}
export const RECEIVE_RESULTS = 'RECEIVE_RESULTS';
export const RECEIVE_RESULTS = 'RECEIVE_RESULTS'
export function receiveResults(json) {
return {
type: RECEIVE_RESULTS,
payload: json,
receivedAt: Date.now(),
};
}
}
export const REMOVE_RESULTS = 'REMOVE_RESULTS';
export const REMOVE_RESULTS = 'REMOVE_RESULTS'
export function removeResults() {
return {
type: REMOVE_RESULTS,
};
}
}

View File

@ -1,13 +1,17 @@
import { h } from 'preact';
import { h } from 'preact'
import formatTime from '../util/formatTime';
import formatTime from '../util/formatTime'
export default (props) => (
<li>
<span class="line">{props.Line.Name}</span>
<span class='line'>{props.Line.Name}</span>
<ul>
<li>{formatTime(props.DepDateTime)} {props.From.Name}</li>
<li>{formatTime(props.ArrDateTime)} {props.To.Name}</li>
<li>
{formatTime(props.DepDateTime)} {props.From.Name}
</li>
<li>
{formatTime(props.ArrDateTime)} {props.To.Name}
</li>
</ul>
</li>
);
)

View File

@ -1,12 +1,12 @@
import { h, Component } from 'preact';
import { h, Component } from 'preact'
import Link from './Link';
import Link from './Link'
import formatTime from '../util/formatTime';
import formatTime from '../util/formatTime'
export default class Result extends Component {
toggle() {
console.log('toggle');
console.log('toggle')
this.setState({
expand: !this.state.expand,
})
@ -17,9 +17,11 @@ export default class Result extends Component {
<li className={{ expand }} onClick={() => this.toggle()}>
{formatTime(props.DepDateTime)} - {formatTime(props.ArrDateTime)}
<ul>
{props.RouteLinks.RouteLink.map((link, i) => <Link key={i} {...link} />)}
{props.RouteLinks.RouteLink.map((link, i) => (
<Link key={i} {...link} />
))}
</ul>
</li>
);
)
}
}

View File

@ -1,24 +1,21 @@
import { h, Component } from 'preact';
import { h, Component } from 'preact'
import Result from './Result';
import store from '../store';
import Result from './Result'
import store from '../store'
export default class ResultList extends Component {
componentDidMount() {
this.unsubscribe = store.subscribe(() => this.forceUpdate());
this.unsubscribe = store.subscribe(() => this.forceUpdate())
}
componentWillUnmount() {
this.unsubscribe();
this.unsubscribe()
}
render() {
const { results } = store.getState();
console.log(results);
const { results } = store.getState()
console.log(results)
return (
<ul>{results && results.map((result, i) => <Result key={i} {...result} />)}</ul>
);
return <ul>{results && results.map((result, i) => <Result key={i} {...result} />)}</ul>
}
}

View File

@ -1,13 +1,13 @@
import { $, $$ } from 'dollr';
import dragula from 'dragula';
import { $, $$ } from 'dollr'
import dragula from 'dragula'
import { h, render } from 'preact';
import ResultList from './components/ResultList';
import { h, render } from 'preact'
import ResultList from './components/ResultList'
import store from './store';
import { receiveResults } from './actions/results';
const result = $('pre');
const containers = $$('.location');
import store from './store'
import { receiveResults } from './actions/results'
const result = $('pre')
const containers = $$('.location')
const drake = dragula(containers, {
revertOnSpill: true,
@ -18,10 +18,10 @@ const drake = dragula(containers, {
ignoreInputTextSelection: false,
// }
});
})
drake.on('drop', (el, target, source) => {
drake.cancel();
drake.cancel()
if (target !== source) {
fetch('/api/trip', {
@ -34,37 +34,36 @@ drake.on('drop', (el, target, source) => {
from: source.dataset.location,
to: target.dataset.location,
}),
}).then((res) => {
return res.json();
}).then((json) => {
console.log(json);
})
.then((res) => {
return res.json()
})
.then((json) => {
console.log(json)
// result.textContent = JSON.stringify(json, null, ' ')
store.dispatch(receiveResults(json));
}).catch((err) => {
console.log('error');
console.log(err);
});
store.dispatch(receiveResults(json))
})
.catch((err) => {
console.log('error')
console.log(err)
})
}
});
})
function prevent(e) {
e.preventDefault();
e.preventDefault()
}
drake.on('over', (el, target, source) => {
if (target !== source) {
target.classList.add('over');
target.classList.add('over')
}
});
})
drake.on('out', (el, target, source) => {
if (target !== source) {
target.classList.remove('over');
target.classList.remove('over')
}
});
render(
<ResultList />,
$('#results')
);
})
render(<ResultList />, $('#results'))

View File

@ -1,26 +1,44 @@
import { h } from 'jsx-node';
import { h } from 'jsx-node'
export default ({ articleUrl, protocol, hostname, websocketsPort, INITIAL_STATE, js, css, cssFile }) => {
return '<!doctype html>' + (
return (
'<!doctype html>' +
(
<html>
<head>
<title>Journey</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
<link type="text/css" rel="stylesheet" href={`/css/main` + (css ? css.suffix : '') + '.css'} />
<meta charset='UTF-8' />
<meta name='viewport' content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' />
<link type='text/css' rel='stylesheet' href={`/css/main` + (css ? css.suffix : '') + '.css'} />
</head>
<body>
<div class="container">
<div data-location="home" class="location l01"><div data-location="home" class="item"><span>Home</span></div></div>
<div data-location="office" class="location l02"><div data-location="office" class="item"><span>Office</span></div></div>
<div data-location="brother" class="location l03"><div data-location="brother" class="item"><span>Brother</span></div></div>
<div data-location="therapist" class="location l04"><div data-location="therapist" class="item"><span>The Rapist</span></div></div>
<div class='container'>
<div data-location='home' class='location l01'>
<div data-location='home' class='item'>
<span>Home</span>
</div>
<div id="results"></div>
<script src={"/js/app" + (js ? js.suffix : '') + '.js'} />
</div>
<div data-location='office' class='location l02'>
<div data-location='office' class='item'>
<span>Office</span>
</div>
</div>
<div data-location='brother' class='location l03'>
<div data-location='brother' class='item'>
<span>Brother</span>
</div>
</div>
<div data-location='therapist' class='location l04'>
<div data-location='therapist' class='item'>
<span>The Rapist</span>
</div>
</div>
</div>
<div id='results' />
<script src={'/js/app' + (js ? js.suffix : '') + '.js'} />
</body>
</html>
);
};
)
)
}

View File

@ -1,10 +1,12 @@
import { h } from 'jsx-node';
import { h } from 'jsx-node'
export default ({ error = {}, regions = {} }) => (
<section className="error page">
<section className='error page'>
<h1>Oops!</h1>
<p>Ett problem har tyvärr uppstått.</p>
<h2>{error.status} {error.statusText}</h2>
<h2>
{error.status} {error.statusText}
</h2>
<p>{error.message}</p>
</section>
);
)

View File

@ -1,16 +1,12 @@
import {
RECEIVE_RESULTS,
REMOVE_RESULTS,
} from '../actions/results';
import { RECEIVE_RESULTS, REMOVE_RESULTS } from '../actions/results'
export default (state = null, action) => {
switch (action.type) {
case RECEIVE_RESULTS:
return action.payload || [];
return action.payload || []
case REMOVE_RESULTS:
return null;
return null
default:
return state;
return state
}
}
};

View File

@ -1,7 +1,7 @@
import { combineReducers } from 'redux';
import { combineReducers } from 'redux'
import results from './results';
import results from './results'
export default combineReducers({
results,
});
})

View File

@ -1,15 +1,9 @@
import thunkMiddleware from 'redux-thunk';
import createLogger from 'redux-logger';
import { createStore, applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk'
import createLogger from 'redux-logger'
import { createStore, applyMiddleware } from 'redux'
const loggerMiddleware = createLogger();
import rootReducer from './reducers/root'
import rootReducer from './reducers/root';
const loggerMiddleware = createLogger()
export default createStore(
rootReducer,
applyMiddleware(
thunkMiddleware,
loggerMiddleware
)
);
export default createStore(rootReducer, applyMiddleware(thunkMiddleware, loggerMiddleware))

View File

@ -1,3 +1,3 @@
export default function formatDateTime(str) {
return str.split('T')[1].slice(0, -3);
return str.split('T')[1].slice(0, -3)
}

View File

@ -4,6 +4,8 @@
"description": "",
"main": "server/server.js",
"scripts": {
"format": "prettier --write .",
"lint": "eslint --ext .js --ext .jsx --ext .mjs .",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Linus Miller <lohfu@lohfu.io> (https://lohfu.io/)",
@ -36,11 +38,16 @@
},
"devDependencies": {
"app-module-path": "^1.1.0",
"eslint": "^3.15.0",
"eslint-config-airbnb": "^14.1.0",
"eslint-config-airbnb-base": "^11.1.0",
"eslint-plugin-import": "^2.2.0",
"eslint-plugin-jsx-a11y": "^4.0.0",
"eslint-plugin-react": "^6.9.0"
"eslint": "^7.4.0",
"eslint-config-prettier": "^6.11.0",
"eslint-config-standard": "^14.1.1",
"eslint-config-standard-react": "^9.2.0",
"eslint-import-resolver-typescript": "^2.0.0",
"eslint-plugin-import": "^2.22.0",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-react": "^7.20.3",
"eslint-plugin-standard": "^4.0.1",
"prettier": "^2.1.1"
}
}

18
prettier.config.js Normal file
View File

@ -0,0 +1,18 @@
'use strict'
module.exports = {
jsxSingleQuote: true,
printWidth: 120,
semi: false,
singleQuote: true,
trailingComma: 'all',
overrides: [
{
files: '*.scss',
options: {
trailingComma: 'none',
},
},
],
}

7
server/.eslintrc Normal file
View File

@ -0,0 +1,7 @@
{
"extends": ["../.eslintrc"],
"env": {
"node": true
}
}

View File

@ -1,7 +1,7 @@
'use strict';
'use strict'
const p = require('path');
const p = require('path')
module.exports = {
static: p.join(PWD, 'public'),
};
}

View File

@ -1,14 +1,14 @@
'use strict';
'use strict'
const _ = require('lodash');
const _ = require('lodash')
const errorTemplate = require('../../build/pages/Error');
const errorTemplate = require('../../build/pages/Error')
const defaults = {
post: (req, res, next) => {
res.template = errorTemplate;
res.template = errorTemplate
next();
next()
},
mystify: {
@ -19,11 +19,13 @@ const defaults = {
// if database = true there has to be a mongoose model name ErrorModel
ignore: [],
},
};
}
const store = require('midwest-service-errors/stores/postgres');
const store = require('midwest-service-errors/stores/postgres')
module.exports = _.merge(defaults, {
module.exports = _.merge(
defaults,
{
development: {
log: {
store,
@ -48,4 +50,5 @@ module.exports = _.merge(defaults, {
console: false,
},
},
}[ENV]);
}[ENV],
)

View File

@ -1,4 +1,4 @@
'use strict';
'use strict'
// global.LOGIN_USER = 'linus.miller@bitmill.co';
// global.LOGIN_USER = 'zarac@zarac.se';

View File

@ -1,10 +1,10 @@
'use strict';
'use strict'
const _ = require('lodash');
const _ = require('lodash')
const config = {
site: require('./site'),
};
}
module.exports = {
invite: {
@ -52,7 +52,7 @@ module.exports = {
noUserFound: 'No user registered with that email.',
noExternalUser: 'The account is not connected to this website.',
externalLoginFailed: 'External login failed.',
emailNotVerified: 'This account\'s email has not been verified.',
emailNotVerified: "This account's email has not been verified.",
banned: 'User is banned.',
blocked: 'User is blocked due to too many login attempts.',
},
@ -78,7 +78,6 @@ module.exports = {
// callbackURL: p.join(config.site.domain, '/auth/facebook/callback'),
// passReqToCallback: true
// },
},
userColumns: [
@ -89,18 +88,21 @@ module.exports = {
'dateMuted',
'dateVerified',
// ['array(SELECT name FROM user_roles LEFT OUTER JOIN roles ON user_roles.role_id = roles.id WHERE user_roles.user_id = users.id)', 'roles'],
[`(SELECT array_to_json(array_agg(row_to_json(d)))
[
`(SELECT array_to_json(array_agg(row_to_json(d)))
FROM (
SELECT id, name
FROM user_roles
LEFT OUTER JOIN roles ON user_roles.role_id = roles.id WHERE user_roles.user_id = users.id
ORDER BY roles.id DESC
) d
)`, 'roles'],
)`,
'roles',
],
],
// needs to be even
tokenLength: 64,
// needs to be even
saltLength: 16,
};
}

View File

@ -1,10 +1,10 @@
'use strict';
'use strict'
const basePort = 3060;
const basePort = 3060
module.exports = {
development: basePort,
testing: basePort + 1,
staging: basePort + 2,
production: basePort + 3,
}[ENV];
}[ENV]

View File

@ -1,4 +1,4 @@
'use strict';
'use strict'
const defaults = {
user: 'newseri_supreme', // env var: PGUSER
@ -10,7 +10,6 @@ const defaults = {
port: 6543, // env var: PGPORT
max: 10, // max number of clients in the pool
idleTimeoutMillis: 30000, // how long a client is allowed to remain idle before being closed
};
}
module.exports = Object.assign(defaults, {
}[ENV]);
module.exports = Object.assign(defaults, {}[ENV])

View File

@ -1,38 +1,38 @@
'use strict';
'use strict'
const chalk = require('chalk');
const session = require('express-session');
const chalk = require('chalk')
const session = require('express-session')
let redisStore;
let redisStore
const config = {
secret: 'asdfpoi7u987777777777777777777sdkafjxxjasdhfhsadfhashdfh`1111111khjjashdfkasjhdflGGGGGGGGGGaaa^^^^^^^^^^yaghsdfqw3u7679`',
secret:
'asdfpoi7u987777777777777777777sdkafjxxjasdhfhsadfhashdfh`1111111khjjashdfkasjhdflGGGGGGGGGGaaa^^^^^^^^^^yaghsdfqw3u7679`',
resave: false,
saveUninitialized: true,
};
}
const redisConfig = {
host: 'localhost',
port: 6379,
};
if (ENV === 'production') {
const RedisStore = require('connect-redis')(require('express-session'));
redisStore = new RedisStore(redisConfig);
redisStore.on('connect', () => {
console.info(`[${chalk.cyan('INIT')}] Redis connected succcessfully`);
});
redisStore.on('disconnect', () => {
throw new Error('Unable to connect to redis. Has it been started?');
});
config.store = redisStore;
} else {
config.store = new session.MemoryStore();
}
module.exports = config;
if (ENV === 'production') {
const RedisStore = require('connect-redis')(require('express-session'))
redisStore = new RedisStore(redisConfig)
redisStore.on('connect', () => {
console.info(`[${chalk.cyan('INIT')}] Redis connected succcessfully`)
})
redisStore.on('disconnect', () => {
throw new Error('Unable to connect to redis. Has it been started?')
})
config.store = redisStore
} else {
config.store = new session.MemoryStore()
}
module.exports = config

View File

@ -1,4 +1,4 @@
'use strict';
'use strict'
module.exports = {
'https://cdnjs.cloudflare.com/ajax/libs/es5-shim/4.5.9/es5-shim.min.js': [
@ -31,4 +31,4 @@ module.exports = {
'ie <= 11',
'safari <= 9',
],
};
}

View File

@ -1,8 +1,8 @@
'use strict';
'use strict'
const _ = require('lodash');
const _ = require('lodash')
const domain = 'newseri.com';
const domain = 'newseri.com'
const defaults = {
domain,
@ -10,10 +10,10 @@ const defaults = {
name: 'newseri-admin',
protocol: 'http',
get host() {
return this.port ? this.hostname + ':' + this.port : this.hostname;
return this.port ? this.hostname + ':' + this.port : this.hostname
},
get url() {
return this.protocol + '://' + this.host + '/';
return this.protocol + '://' + this.host + '/'
},
emails: {
robot: 'no-reply@thecodebureau.com',
@ -21,9 +21,11 @@ const defaults = {
webmaster: 'webmaster@thecodebureau.com',
order: 'info@thecodebureau.com',
},
};
}
module.exports = _.merge(defaults, {
module.exports = _.merge(
defaults,
{
development: {
hostname: 'localhost',
port: process.env.EXTERNAL_PORT || process.env.PORT || require('./port'),
@ -48,4 +50,5 @@ module.exports = _.merge(defaults, {
// order: 'order@' + domain,
// },
},
}[ENV]);
}[ENV],
)

View File

@ -1,6 +1,6 @@
'use strict';
'use strict'
const _ = require('lodash');
const _ = require('lodash')
const defaults = {
auth: {
@ -10,6 +10,6 @@ const defaults = {
},
host: 'smtp.sparkpostmail.com',
port: 587,
};
}
module.exports = _.merge(defaults, {}[ENV]);
module.exports = _.merge(defaults, {}[ENV])

View File

@ -1,6 +1,6 @@
'use strict';
'use strict'
const factory = require('midwest/util/db');
const conf = require('./config/postgres');
const factory = require('midwest/util/db')
const conf = require('./config/postgres')
module.exports = factory(conf);
module.exports = factory(conf)

View File

@ -1,4 +1,4 @@
'use strict';
'use strict'
// const requireDir = require('require-dir');
// const membership = require('midwest-module-membership');
@ -6,5 +6,4 @@
// const config = requireDir('./config', { camelcase: true });
// const db = require('./db');
// membership.configure(Object.assign({ db, site: config.site, smtp: config.smtp }, config.membership));

View File

@ -1,32 +1,28 @@
'use strict';
'use strict'
const { h } = require('jsx-node');
const { h } = require('jsx-node')
module.exports = function (Component, Master) {
const locals = Object.assign({ query: this.req.query }, this.app.locals, this.locals);
const locals = Object.assign({ query: this.req.query }, this.app.locals, this.locals)
let html;
let html
if (typeof Master === 'function') {
if (typeof Component === 'function') {
return this.send(
h(Master, locals,
h(Component, locals)
)
);
return this.send(h(Master, locals, h(Component, locals)))
}
Component = Master;
Component = Master
}
if (typeof Component !== 'function') {
throw new Error('Not a Component');
throw new Error('Not a Component')
} else if (Component.prototype && Component.prototype.render) {
const i = new Component(locals);
html = i.render(i.props, i.state);
const i = new Component(locals)
html = i.render(i.props, i.state)
} else {
html = Component(locals);
html = Component(locals)
}
this.send(html);
};
this.send(html)
}

View File

@ -1,14 +1,13 @@
'use strict';
'use strict'
const format = require('easy-tz/cjs/format')
const format = require('easy-tz/cjs/format');
const request = require('superagent');
const request = require('superagent')
// import get from 'get-value';
const _ = require('lodash');
const _ = require('lodash')
const xml2json = require('xml2json');
const xml2json = require('xml2json')
// const to = 'Lund Mellanvångsvägen';
// const from = 'Malmö Triangeln';
@ -40,47 +39,49 @@ const stations = {
name: 'Malmö Triangeln',
type: 'STOP_AREA',
},
};
const types = {
'STOP_AREA': 0,
}
const router = new (require('express')).Router();
const types = {
STOP_AREA: 0,
}
const router = new (require('express').Router)()
function formatStation(json) {
return `${encodeURIComponent(json.name)}|${json.id}|${types[json.type]}`
}
function formatTime(date) {
date = date || new Date();
return format(null, 'YYYY-MM-DD HH:mm', date);
date = date || new Date()
return format(null, 'YYYY-MM-DD HH:mm', date)
}
console.log(formatTime());
console.log(formatTime())
function formatLink(link) {
}
function formatLink(link) {}
function formatResult(result) {
return _.omit(result, 'Prices');
return _.omit(result, 'Prices')
}
console.log(new Date('2017-02-24T17:16:00'.split('T').join(' ')).toLocaleString());
console.log(new Date('2017-02-24T17:16:00'.split('T').join(' ')).toLocaleString())
const journeysPath = ['soap:Envelope', 'soap:Body', 'GetJourneyResponse', 'GetJourneyResult', 'Journeys', 'Journey']
// http://www.labs.skanetrafiken.se/v2.2/resultspage.asp?cmdaction=next&selPointFr=malm%F6%20C|80000|0&selPointTo=landskrona|82000|0&LastStart=2017-02-23%2016:38
router.post('/trip', (req, res, next) => {
request(`http://www.labs.skanetrafiken.se/v2.2/resultspage.asp?cmdaction=next&selPointFr=${formatStation(stations[req.body.from])}&selPointTo=${formatStation(stations[req.body.to])}&LastStart=${encodeURIComponent(formatTime(req.body.datetime))}`).then((response) =>{
const result = _.get(xml2json.toJson(response.text, { object: true }), journeysPath);
request(
`http://www.labs.skanetrafiken.se/v2.2/resultspage.asp?cmdaction=next&selPointFr=${formatStation(
stations[req.body.from],
)}&selPointTo=${formatStation(stations[req.body.to])}&LastStart=${encodeURIComponent(
formatTime(req.body.datetime),
)}`,
).then((response) => {
const result = _.get(xml2json.toJson(response.text, { object: true }), journeysPath)
result.forEach(formatResult);
result.forEach(formatResult)
res.json(result);
});
});
res.json(result)
})
})
module.exports = router;
module.exports = router

View File

@ -1,16 +1,16 @@
'use strict';
'use strict'
// const masterTemplate = require('../client/public/components/Master');
const masterTemplate = require('../../build/master');
const masterTemplate = require('../../build/master')
// const loginFormTemplate = require('../build/components/login-form/template');
// const registerFormTemplate = require('../build/components/register-form/template');
// const changePasswordFormTemplate = require('../build/components/change-password-form/template');
// const forgotPasswordFormTemplate = require('../build/components/forgot-password-form/template');
// const bareMasterTemplate = require('../build/bare-master');
const router = new (require('express')).Router();
const router = new (require('express').Router)()
const startCase = require('lodash/startCase');
const startCase = require('lodash/startCase')
const mw = {
// employees: require('midwest-service-employees/middleware'),
@ -24,7 +24,7 @@ const mw = {
// roles: require('midwest-module-membership/services/roles/middleware'),
// users: require('../services/users/users-middleware'),
shim: require('midwest/factories/shim')(require('../config/shim')),
};
}
// const {
// isAuthenticated,
@ -33,7 +33,7 @@ const mw = {
// redirectAuthorized,
// } = require('midwest-module-membership/passport/authorization-middleware');
const allowedRoutes = ['forgot', 'reset', 'verify', 'login', 'register'];
const allowedRoutes = ['forgot', 'reset', 'verify', 'login', 'register']
// const config = {
// membership: require('../config/membership'),
@ -45,11 +45,11 @@ router
// .get(new RegExp(`/(?!(${allowedRoutes.join('|')}))`), isAuthenticated, redirectUnauthorized(config.membership.paths.login))
// .get(new RegExp(`/(?=(${allowedRoutes.join('|')}))`), redirectAuthorized(isAuthenticated, '/'))
.get('/', mw.shim, (req, res, next) => {
res.preventFlatten = true;
res.preventFlatten = true
res.master = masterTemplate;
res.master = masterTemplate
next();
next()
})
// .get(new RegExp(`/${allowedRoutes.join('|')}`), redirectAuthenticated('/'), (req, res, next) => {
// res.preventFlatten = true;
@ -101,6 +101,5 @@ router
// .get('/forgot')
// .get('/reset')
// .get('/verify')
;
module.exports = router;
module.exports = router

View File

@ -1,4 +1,4 @@
'use strict';
'use strict'
/*
* The main file that sets up the Express instance and node
@ -7,49 +7,49 @@
* @type {Express instance}
*/
global.ENV = process.env.NODE_ENV || 'development';
global.PWD = process.env.NODE_PWD || process.cwd();
global.ENV = process.env.NODE_ENV || 'development'
global.PWD = process.env.NODE_PWD || process.cwd()
// modules > native
const p = require('path');
const p = require('path')
if (ENV === 'development') {
// output filename in console log and colour console.dir
require('midwest/util/console');
require('midwest/util/console')
// needed so symlinked modules get access to main projects node_modules/
require('app-module-path').addPath(p.join(PWD, 'node_modules'));
require('app-module-path').addPath(p.join(PWD, 'node_modules'))
}
// modules > 3rd party
const _ = require('lodash');
const chalk = require('chalk');
const express = require('express');
const _ = require('lodash')
const chalk = require('chalk')
const express = require('express')
// const passport = require('passport');
const requireDir = require('require-dir');
const requireDir = require('require-dir')
// modules > express middlewares
const bodyParser = require('body-parser');
const bodyParser = require('body-parser')
// const session = require('express-session');
// const cookieParser = require('cookie-parser');
// modules > midwest
const colorizeStack = require('midwest/util/colorize-stack');
const colorizeStack = require('midwest/util/colorize-stack')
// make error output stack pretty
process.on('uncaughtException', (err) => {
console.error(chalk.red('UNCAUGHT EXCEPTION'));
console.error(chalk.red('UNCAUGHT EXCEPTION'))
if (err.stack) {
console.error(colorizeStack(err.stack));
console.error(colorizeStack(err.stack))
} else {
console.error(err);
console.error(err)
}
process.exit(1);
});
process.exit(1)
})
// midwest modules and services configuration
require('./midwest');
require('./midwest')
const config = requireDir('./config', { camelcase: true });
const config = requireDir('./config', { camelcase: true })
const prewares = [
express.static(config.dir.static, ENV === 'production' ? { maxAge: '1 year' } : null),
@ -59,11 +59,11 @@ const prewares = [
// session(config.session),
// passport.initialize(),
// passport.session(),
];
]
if (ENV === 'development') {
// only log requests to console in development mode
prewares.unshift(require('morgan')('dev'));
prewares.unshift(require('morgan')('dev'))
// prewares.push(require('midwest-module-membership/passport/automatic-login'));
}
@ -73,45 +73,47 @@ const postwares = [
require('midwest/factories/error-handler')(config.errorHandler),
// respond
require('midwest/middleware/responder'),
];
]
const server = express();
const server = express()
// get IP & whatnot from nginx proxy
server.set('trust proxy', true);
server.set('trust proxy', true)
_.extend(server.locals, {
site: require('./config/site'),
});
})
// override default response render method for
// more convenient use with marko
server.response.render = require('./render');
server.response.render = require('./render')
try {
server.locals.js = require(p.join(PWD, 'public/js.json'));
server.locals.js = require(p.join(PWD, 'public/js.json'))
} catch (e) {}
try {
server.locals.css = require(p.join(PWD, 'public/css.json'));
server.locals.css = require(p.join(PWD, 'public/css.json'))
} catch (e) {}
// load prewares
server.use(...prewares);
server.use(...prewares)
// mount routers
server.use(require('./routers/index'));
server.use('/api', require('./routers/api'));
server.use(require('./routers/index'))
server.use('/api', require('./routers/api'))
// server.use('/auth', require('midwest-module-membership/passport/router'));
// load postwares
server.use(...postwares);
server.use(...postwares)
// Only start Express server when it is the main module (ie not required by test)
if (require.main === module) {
server.http = server.listen(config.port, () => {
console.info(`[${chalk.cyan('INIT')}] HTTP Server listening on port ${chalk.magenta(config.port)} (${chalk.yellow(ENV)})`);
});
console.info(
`[${chalk.cyan('INIT')}] HTTP Server listening on port ${chalk.magenta(config.port)} (${chalk.yellow(ENV)})`,
)
})
}
module.exports = server;
module.exports = server