diff --git a/.eslintignore b/.eslintignore
new file mode 100644
index 0000000..01af582
--- /dev/null
+++ b/.eslintignore
@@ -0,0 +1,2 @@
+/build
+/dump
diff --git a/.eslintrc b/.eslintrc
new file mode 100644
index 0000000..8cafca0
--- /dev/null
+++ b/.eslintrc
@@ -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
+ }
+}
diff --git a/assets/less/dragula.less b/assets/less/dragula.less
index 28578f4..3af2219 100644
--- a/assets/less/dragula.less
+++ b/assets/less/dragula.less
@@ -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);
}
diff --git a/assets/less/main.less b/assets/less/main.less
index a2e72cc..0eca8c9 100644
--- a/assets/less/main.less
+++ b/assets/less/main.less
@@ -1,4 +1,4 @@
-@import "./dragula";
+@import './dragula';
div.container {
width: 100%;
diff --git a/client/.eslintrc b/client/.eslintrc
new file mode 100644
index 0000000..e38330e
--- /dev/null
+++ b/client/.eslintrc
@@ -0,0 +1,7 @@
+{
+ "extends": ["../.eslintrc", "standard-jsx", "prettier/react"],
+
+ "env": {
+ "browser": true
+ }
+}
diff --git a/client/actions/results.js b/client/actions/results.js
index e2d2532..cacadd0 100644
--- a/client/actions/results.js
+++ b/client/actions/results.js
@@ -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((json) => {
- const actions = [receiveResults(json.results || [])];
+ })
+ .then((res) => res.json())
+ .then((json) => {
+ const actions = [receiveResults(json.results || [])]
- if (json.perPage) {
- actions.push(setPagination(pick(json, 'perPage', 'totalCount')));
- }
+ if (json.perPage) {
+ 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,
- };
+ }
}
diff --git a/client/components/Link.jsx b/client/components/Link.jsx
index 800b538..094bfd4 100644
--- a/client/components/Link.jsx
+++ b/client/components/Link.jsx
@@ -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) => (
- {props.Line.Name}
+ {props.Line.Name}
- - {formatTime(props.DepDateTime)} {props.From.Name}
- - {formatTime(props.ArrDateTime)} {props.To.Name}
+ -
+ {formatTime(props.DepDateTime)} {props.From.Name}
+
+ -
+ {formatTime(props.ArrDateTime)} {props.To.Name}
+
-);
+)
diff --git a/client/components/Result.jsx b/client/components/Result.jsx
index 87e1460..5f3ae4a 100644
--- a/client/components/Result.jsx
+++ b/client/components/Result.jsx
@@ -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 {
this.toggle()}>
{formatTime(props.DepDateTime)} - {formatTime(props.ArrDateTime)}
- {props.RouteLinks.RouteLink.map((link, i) => )}
+ {props.RouteLinks.RouteLink.map((link, i) => (
+
+ ))}
- );
+ )
}
}
diff --git a/client/components/ResultList.jsx b/client/components/ResultList.jsx
index 39f5f52..c59230c 100644
--- a/client/components/ResultList.jsx
+++ b/client/components/ResultList.jsx
@@ -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 (
- {results && results.map((result, i) => )}
- );
+ return {results && results.map((result, i) => )}
}
}
-
diff --git a/client/index.js b/client/index.js
index 4a5b9be..1f6eeca 100644
--- a/client/index.js
+++ b/client/index.js
@@ -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,
@@ -16,12 +16,12 @@ const drake = dragula(containers, {
// // console.log(target);
// return true;
- ignoreInputTextSelection: false,
+ 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);
- // result.textContent = JSON.stringify(json, null, ' ')
- store.dispatch(receiveResults(json));
- }).catch((err) => {
- console.log('error');
- console.log(err);
- });
+ })
+ .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)
+ })
}
-});
+})
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(
- ,
- $('#results')
-);
+})
+render(, $('#results'))
diff --git a/client/master.jsx b/client/master.jsx
index ee553ca..344dc13 100644
--- a/client/master.jsx
+++ b/client/master.jsx
@@ -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 '' + (
-
-
- Journey
-
-
-
-
+ return (
+ '' +
+ (
+
+
+ Journey
+
+
+
+
-
-
-
-
-
-
-
- );
-};
+
+
+
+
+
+
+ )
+ )
+}
diff --git a/client/pages/Error.jsx b/client/pages/Error.jsx
index 313f7f8..d78f8e5 100644
--- a/client/pages/Error.jsx
+++ b/client/pages/Error.jsx
@@ -1,10 +1,12 @@
-import { h } from 'jsx-node';
+import { h } from 'jsx-node'
-export default ({ error = {}, regions = {}}) => (
-
+export default ({ error = {}, regions = {} }) => (
+
Oops!
Ett problem har tyvärr uppstått.
- {error.status} {error.statusText}
+
+ {error.status} {error.statusText}
+
{error.message}
-);
+)
diff --git a/client/reducers/results.js b/client/reducers/results.js
index bdaf677..285e130 100644
--- a/client/reducers/results.js
+++ b/client/reducers/results.js
@@ -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
}
-};
-
+}
diff --git a/client/reducers/root.js b/client/reducers/root.js
index 8e8deb0..e4d5dfe 100644
--- a/client/reducers/root.js
+++ b/client/reducers/root.js
@@ -1,7 +1,7 @@
-import { combineReducers } from 'redux';
+import { combineReducers } from 'redux'
-import results from './results';
+import results from './results'
export default combineReducers({
results,
-});
+})
diff --git a/client/store.js b/client/store.js
index 4044499..04fb63a 100644
--- a/client/store.js
+++ b/client/store.js
@@ -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))
diff --git a/client/util/formatTime.js b/client/util/formatTime.js
index 2800c42..9162c87 100644
--- a/client/util/formatTime.js
+++ b/client/util/formatTime.js
@@ -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)
}
diff --git a/package.json b/package.json
index dda4952..5d1b429 100644
--- a/package.json
+++ b/package.json
@@ -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 (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"
}
}
diff --git a/prettier.config.js b/prettier.config.js
new file mode 100644
index 0000000..a04fe6c
--- /dev/null
+++ b/prettier.config.js
@@ -0,0 +1,18 @@
+'use strict'
+
+module.exports = {
+ jsxSingleQuote: true,
+ printWidth: 120,
+ semi: false,
+ singleQuote: true,
+ trailingComma: 'all',
+
+ overrides: [
+ {
+ files: '*.scss',
+ options: {
+ trailingComma: 'none',
+ },
+ },
+ ],
+}
diff --git a/server/.eslintrc b/server/.eslintrc
new file mode 100644
index 0000000..a08e166
--- /dev/null
+++ b/server/.eslintrc
@@ -0,0 +1,7 @@
+{
+ "extends": ["../.eslintrc"],
+
+ "env": {
+ "node": true
+ }
+}
diff --git a/server/config/dir.js b/server/config/dir.js
index 1ad5a4b..20c1347 100644
--- a/server/config/dir.js
+++ b/server/config/dir.js
@@ -1,7 +1,7 @@
-'use strict';
+'use strict'
-const p = require('path');
+const p = require('path')
module.exports = {
static: p.join(PWD, 'public'),
-};
+}
diff --git a/server/config/error-handler.js b/server/config/error-handler.js
index 36db38f..343b9c2 100644
--- a/server/config/error-handler.js
+++ b/server/config/error-handler.js
@@ -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,33 +19,36 @@ 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, {
- development: {
- log: {
- store,
- console: true,
+module.exports = _.merge(
+ defaults,
+ {
+ development: {
+ log: {
+ store,
+ console: true,
+ },
},
- },
- testing: {
- log: {
- store: false,
- console: false,
+ testing: {
+ log: {
+ store: false,
+ console: false,
+ },
},
- },
- staging: {
- log: {
- store,
- console: false,
+ staging: {
+ log: {
+ store,
+ console: false,
+ },
},
- },
- production: {
- log: {
- store,
- console: false,
+ production: {
+ log: {
+ store,
+ console: false,
+ },
},
- },
-}[ENV]);
+ }[ENV],
+)
diff --git a/server/config/globals.js b/server/config/globals.js
index 14fa682..403bb38 100644
--- a/server/config/globals.js
+++ b/server/config/globals.js
@@ -1,4 +1,4 @@
-'use strict';
+'use strict'
// global.LOGIN_USER = 'linus.miller@bitmill.co';
// global.LOGIN_USER = 'zarac@zarac.se';
diff --git a/server/config/membership.js b/server/config/membership.js
index 2bf993c..519f05b 100644
--- a/server/config/membership.js
+++ b/server/config/membership.js
@@ -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.',
},
@@ -71,14 +71,13 @@ module.exports = {
scope: ['email'],
- //providers: {
+ // providers: {
// facebook: {
// clientID: 'change-this-fool',
// clientSecret: 'change-this-fool',
// 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,
-};
+}
diff --git a/server/config/port.js b/server/config/port.js
index 6bfd088..5ddeaf6 100644
--- a/server/config/port.js
+++ b/server/config/port.js
@@ -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]
diff --git a/server/config/postgres.js b/server/config/postgres.js
index 12656f6..99220eb 100644
--- a/server/config/postgres.js
+++ b/server/config/postgres.js
@@ -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])
diff --git a/server/config/session.js b/server/config/session.js
index 090558d..18f06c0 100644
--- a/server/config/session.js
+++ b/server/config/session.js
@@ -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
diff --git a/server/config/shim.js b/server/config/shim.js
index 494cf40..cf6e90d 100644
--- a/server/config/shim.js
+++ b/server/config/shim.js
@@ -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': [
@@ -9,8 +9,8 @@ module.exports = {
'safari <= 5',
],
'https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.35.1/es6-shim.min.js': [
- // 'https://cdnjs.cloudflare.com/ajax/libs/core-js/2.4.1/core.min.js': [
- // 'https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.16.0/polyfill.js': [
+ // 'https://cdnjs.cloudflare.com/ajax/libs/core-js/2.4.1/core.min.js': [
+ // 'https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.16.0/polyfill.js': [
'chrome <= 51',
'edge <= 13',
'firefox <= 44',
@@ -31,4 +31,4 @@ module.exports = {
'ie <= 11',
'safari <= 9',
],
-};
+}
diff --git a/server/config/site.js b/server/config/site.js
index 317b9f5..85c2c9e 100644
--- a/server/config/site.js
+++ b/server/config/site.js
@@ -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,31 +21,34 @@ const defaults = {
webmaster: 'webmaster@thecodebureau.com',
order: 'info@thecodebureau.com',
},
-};
+}
-module.exports = _.merge(defaults, {
- development: {
- hostname: 'localhost',
- port: process.env.EXTERNAL_PORT || process.env.PORT || require('./port'),
- },
+module.exports = _.merge(
+ defaults,
+ {
+ development: {
+ hostname: 'localhost',
+ port: process.env.EXTERNAL_PORT || process.env.PORT || require('./port'),
+ },
- testing: {
- hostname: 'localhost',
- port: process.env.PORT || require('./port'),
- },
+ testing: {
+ hostname: 'localhost',
+ port: process.env.PORT || require('./port'),
+ },
- staging: {
- hostname: `admin.${domain}`,
- },
+ staging: {
+ hostname: `admin.${domain}`,
+ },
- production: {
- hostname: `admin.${domain}`,
- protocol: 'https',
- // emails: {
- // robot: 'no-reply@' + domain,
- // info: 'info@' + domain,
- // webmaster: 'webmaster@' + domain,
- // order: 'order@' + domain,
- // },
- },
-}[ENV]);
+ production: {
+ hostname: `admin.${domain}`,
+ protocol: 'https',
+ // emails: {
+ // robot: 'no-reply@' + domain,
+ // info: 'info@' + domain,
+ // webmaster: 'webmaster@' + domain,
+ // order: 'order@' + domain,
+ // },
+ },
+ }[ENV],
+)
diff --git a/server/config/smtp.js b/server/config/smtp.js
index 8dadf7c..39bbe83 100644
--- a/server/config/smtp.js
+++ b/server/config/smtp.js
@@ -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])
diff --git a/server/db.js b/server/db.js
index a46fb9c..73d4ef0 100644
--- a/server/db.js
+++ b/server/db.js
@@ -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)
diff --git a/server/midwest.js b/server/midwest.js
index fcb4a26..8b635f8 100644
--- a/server/midwest.js
+++ b/server/midwest.js
@@ -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));
diff --git a/server/render.js b/server/render.js
index 6b58663..3179faf 100644
--- a/server/render.js
+++ b/server/render.js
@@ -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)
+}
diff --git a/server/routers/api.js b/server/routers/api.js
index 0df11c1..3b40b4a 100644
--- a/server/routers/api.js
+++ b/server/routers/api.js
@@ -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';
@@ -30,7 +29,7 @@ const stations = {
type: 'STOP_AREA',
},
- brother: {
+ brother: {
id: '81831',
name: 'Lund Mellanvångsvägen',
type: 'STOP_AREA',
@@ -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']
+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
diff --git a/server/routers/index.js b/server/routers/index.js
index 8665b71..04c98e9 100644
--- a/server/routers/index.js
+++ b/server/routers/index.js
@@ -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,62 +45,61 @@ 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;
+// .get(new RegExp(`/${allowedRoutes.join('|')}`), redirectAuthenticated('/'), (req, res, next) => {
+// res.preventFlatten = true;
- // res.master = bareMasterTemplate;
+// res.master = bareMasterTemplate;
- // next();
- // })
- // .get('/login', (req, res, next) => {
- // res.locals.scripts = ['/js/login.js'];
+// next();
+// })
+// .get('/login', (req, res, next) => {
+// res.locals.scripts = ['/js/login.js'];
- // res.template = loginFormTemplate;
+// res.template = loginFormTemplate;
- // next();
- // })
- // .get('/register', mw.invites.findByTokenAndEmail, (req, res, next) => {
- // res.locals.scripts = ['/js/register.js'];
+// next();
+// })
+// .get('/register', mw.invites.findByTokenAndEmail, (req, res, next) => {
+// res.locals.scripts = ['/js/register.js'];
- // res.template = registerFormTemplate;
+// res.template = registerFormTemplate;
- // next();
- // })
- // .get('/change-password', (req, res, next) => {
- // res.locals.scripts = ['/js/change-password.js'];
+// next();
+// })
+// .get('/change-password', (req, res, next) => {
+// res.locals.scripts = ['/js/change-password.js'];
- // res.template = changePasswordFormTemplate;
+// res.template = changePasswordFormTemplate;
- // next();
- // })
- // .get('/forgot-password', (req, res, next) => {
- // res.locals.scripts = ['/js/forgot-password.js'];
+// next();
+// })
+// .get('/forgot-password', (req, res, next) => {
+// res.locals.scripts = ['/js/forgot-password.js'];
- // res.template = forgotPasswordFormTemplate;
+// res.template = forgotPasswordFormTemplate;
- // next();
- // .get('/membership/users/:id', mw.publishers.getAll, mw.roles.getAll, mw.users.findById, (req, res, next) => {
- // console.log(res.locals.roles);
- // // res.locals.allRoles = res.locals.roles;
- // // console.log(res.locals);
- // // res.locals.allPublishers = res.locals.publishers.filter((publisher) => !res.locals.user.publishers.some((p) => {
- // // return publisher._id.toString() === p._id.toString();
- // // }));
- // // delete res.locals.roles;
- // // delete res.locals.publishers;
- // next();
- // })
- // .get('/errors', mw.errors.formatQuery, mw.errors.paginate, mw.errors.find)
- // .get('/login')
- // .get('/forgot')
- // .get('/reset')
- // .get('/verify')
-;
+// next();
+// .get('/membership/users/:id', mw.publishers.getAll, mw.roles.getAll, mw.users.findById, (req, res, next) => {
+// console.log(res.locals.roles);
+// // res.locals.allRoles = res.locals.roles;
+// // console.log(res.locals);
+// // res.locals.allPublishers = res.locals.publishers.filter((publisher) => !res.locals.user.publishers.some((p) => {
+// // return publisher._id.toString() === p._id.toString();
+// // }));
+// // delete res.locals.roles;
+// // delete res.locals.publishers;
+// next();
+// })
+// .get('/errors', mw.errors.formatQuery, mw.errors.paginate, mw.errors.find)
+// .get('/login')
+// .get('/forgot')
+// .get('/reset')
+// .get('/verify')
-module.exports = router;
+module.exports = router
diff --git a/server/server.js b/server/server.js
index d947fca..54f55c6 100644
--- a/server/server.js
+++ b/server/server.js
@@ -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