Skip to content

Commit

Permalink
Merge pull request #16 from thecodeorigin/dev/v1.1.2
Browse files Browse the repository at this point in the history
fix: server middleware and axios configuration
  • Loading branch information
imrim12 authored Dec 30, 2021
2 parents 5b01602 + 0654ed7 commit c2772e1
Show file tree
Hide file tree
Showing 12 changed files with 92 additions and 123 deletions.
3 changes: 2 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
API_URL=http://localhost:3000/api/v1
API_URL=http://localhost:3000/api/v1
SERVER_API_URL=http://localhost:3000/secret-api/v1
13 changes: 5 additions & 8 deletions core/plugins/axios.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,22 @@
import dev from '@/core/utils/functions/dev';

export default ({ $axios, store, error: nuxtError }) => {
export default ({ $axios, store }) => {
$axios.onRequest((config) => {
const authToken = store.getters['auth/token'];

if (authToken) {
config.headers.Authorization = 'Bearer ' + authToken;
}
dev.log((authToken ? '[Authenticated] ': '') + 'API executed');
dev.log((authToken ? '[Authenticated] ' : '') + 'API executed');
});

$axios.onResponse((_response) => {});

$axios.onError(async(error) => {
await nuxtError({
statusCode: error.response?.status,
message: error.message,
});
$axios.onError((error) => {
// Handling, refresh token,...
dev.error(error);

return Promise.resolve(false);
return Promise.reject(error);
});

$axios.onRequestError((_err) => {});
Expand Down
48 changes: 20 additions & 28 deletions nuxt.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export default {
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: '' },
{ name: 'format-detection', content: 'telephone=no' }
{ name: 'format-detection', content: 'telephone=no' },
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
Expand All @@ -46,10 +46,7 @@ export default {
},

// Global CSS: https://go.nuxtjs.dev/config-css
css: [
'@/core/styles/css/all.css',
'@/core/styles/scss/all.scss',
],
css: ['@/core/styles/css/all.css', '@/core/styles/scss/all.scss'],

// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [
Expand Down Expand Up @@ -80,10 +77,7 @@ export default {
'@nuxtjs/dotenv',
// https://www.npmjs.com/package/@nuxtjs/style-resources
'@nuxtjs/style-resources',
[
'@nuxtjs/eslint-module',
{ fix: true },
],
['@nuxtjs/eslint-module', { fix: true }],
],

styleResources: {
Expand All @@ -110,10 +104,10 @@ export default {
strategy: 'no_prefix',
vueI18n: {
fallbackLocale: {
vi: ['en'],
default: ['en']
vi: ['en'],
default: ['en'],
},
silentFallbackWarn: true,
silentTranslationWarn: true,
messages: {
en: readYamlFile('./locales/en.yaml'),
vi: readYamlFile('./locales/vi.yaml'),
Expand All @@ -127,7 +121,7 @@ export default {
// baseURL: process.env.API_URL || 'http://localhost:5000',
retry: { retries: 3 },
},

watch: [
'locales',
'app.html',
Expand All @@ -146,8 +140,8 @@ export default {
// PWA module configuration: https://go.nuxtjs.dev/pwa
pwa: {
manifest: {
lang: 'en'
}
lang: 'en',
},
},

terser: {
Expand All @@ -158,9 +152,7 @@ export default {

// Build Configuration: https://go.nuxtjs.dev/config-build
build: {
transpile: [
/^element-ui/,
],
transpile: [/^element-ui/],
extractCSS: {
ignoreOrder: true,
},
Expand All @@ -171,13 +163,16 @@ export default {
babel: {
plugins: [
'@babel/plugin-proposal-optional-chaining',
'@babel/plugin-proposal-nullish-coalescing-operator'
]
'@babel/plugin-proposal-nullish-coalescing-operator',
],
},
loaders: {
cssModules: {
modules: {
localIdentName: process.env.NODE_ENV === 'development' ? '[local]_[hash:base64:5]' : '[hash:base64:8]',
localIdentName:
process.env.NODE_ENV === 'development'
? '[local]_[hash:base64:5]'
: '[hash:base64:8]',
},
},
},
Expand All @@ -191,14 +186,11 @@ export default {
},

router: {
middleware: ['ssr-cookie']
middleware: ['ssr-cookie'],
},

/*
** Server Middleware
*/
serverMiddleware: [
{ path: '/api/v1', handler: '@/server' },
],

** Server Middleware
*/
serverMiddleware: [{ path: '/api/v1', handler: '@/server' }],
};
6 changes: 5 additions & 1 deletion pages/projects.vue
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,11 @@ export default defineComponent({
store.registerModule('project', projectStore);
onMounted(() => {
store.dispatch('project/getMany');
try {
store.dispatch('project/getMany');
} catch (e) {
console.error(e);
}
});
onUnmounted(() => store.unregisterModule('project'));
Expand Down
5 changes: 0 additions & 5 deletions server/config.js

This file was deleted.

9 changes: 0 additions & 9 deletions server/constants/index.js

This file was deleted.

86 changes: 53 additions & 33 deletions server/index.js
Original file line number Diff line number Diff line change
@@ -1,41 +1,61 @@
/* eslint-disable no-console */
import Express from 'express';
import express from 'express';
import chalk from 'chalk';
import { CONFIG } from './config';
import { router } from './routes/index';
import { logger } from './utils/logger';

const app = Express();

app.use(Express.json({ limit: '5mb' }));
import axios from 'axios';
import { logger } from './utils/logger';

const routes = Express.Router();
const app = express();
app.use(express.json());

logger.debug(
`${chalk.red(`(!)`)} Make change to API Routes at: ${chalk.yellow('@/server/routes/**')}\n`
);
router.forEach(route => {
routes[route.method](route.path, route.handlers);
logger.debug(
`${chalk.green(`✓ API Routes ready:`)} ${chalk.yellow(`[${route.method}] ${route.path}`)}`
);
const http = axios.create({
baseURL: process.env.SERVER_API_URL,
// timeout: 10000,
});

app.use(routes);

process.on('SIGINT', function () {
console.log('\nGracefully shutting down from SIGINT (Ctrl-C)');
// some other closing procedures go here
process.exit(1);
app.all('*', async (req, res) => {
const url = req.url;
const method = req.method;
const body = req.body;
const headers = {};

if (req.headers.authorization) {
headers.authorization = req.headers.authorization;
} else if (req.headers.authorization) {
headers.Authorization = req.headers.Authorization;
}

try {
const response = await http.request({
url,
method,
headers,
data: body,
});

logger.debug(
`${chalk.bold.blue(process.env.SERVER_API_URL + url)}: ${chalk.green(
response.status
)}`
);

res.status(response.status).json(response.data);
} catch (err) {
logger.debug(
`${chalk.bold.red(process.env.SERVER_API_URL + url)}: ${chalk.bold.red(
err.response?.status || 500
)} ${err.message}\nHeaders: ${chalk.yellow(
JSON.stringify(Object.keys(headers).filter((k) => k))
)}\nBody: ${chalk.yellow(
JSON.stringify(Object.keys(body || {}).filter((k) => k))
)}`
);

res.status(err.response?.status || 500).json({
status: err.response?.status,
statusText: err.response?.statusText,
error: err.response?.data,
});
}
});

// Export express app
export default app;

// Start standalone server if directly running
if (require.main === module) {
// Start express server
app.listen(CONFIG.PORT, CONFIG.HOST, () => {
console.log(`Server started at http://${CONFIG.HOST}:${CONFIG.PORT} \n`);
});
}
module.exports = app;
10 changes: 0 additions & 10 deletions server/routes/auth.js

This file was deleted.

7 changes: 0 additions & 7 deletions server/routes/index.js

This file was deleted.

12 changes: 0 additions & 12 deletions server/routes/project.js

This file was deleted.

10 changes: 3 additions & 7 deletions server/utils/forward.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,23 +28,19 @@ export const forward = (url) => {
}
});

return res.json({
status: response.status,
statusText: response.statusText,
data: response.data
});
return res.status(response.status).json(response.data);
} catch (error) {
if (CONFIG.IS_DEV) {
logger.debug(
`${chalk.bold.blue(url)}: ${chalk.red(error)}`
);
);
} else {
logger.info(
`${chalk.bold.blue(url)}: ${chalk.red(error)}`
);
}

return next(error);
return res.status(error?.response?.status || 500).json(error?.response?.data);
}
};
};
6 changes: 4 additions & 2 deletions store/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ const cookieparser = process.server ? require('cookieparser') : undefined;

export default {
nuxtServerInit({ commit }, { req }) {
const cookie = cookieparser.parse(req.headers.cookie);
const cookie = cookieparser.parse(req?.headers?.cookie || '');

commit('SET_LOCALE', cookie.lang);
if (cookie) {
commit('SET_LOCALE', cookie.lang || 'en');
}

commit('auth/SET_AUTH', {
user: {
Expand Down

0 comments on commit c2772e1

Please sign in to comment.