From de2f5f41712efa3f063521cca8280c72dc4b46ae Mon Sep 17 00:00:00 2001 From: Emanuele Paolini Date: Thu, 31 Aug 2023 18:55:53 +0200 Subject: [PATCH] =?UTF-8?q?riprogettata=20comunicazione=20API=20con=20Fran?= =?UTF-8?q?cesco:=20*=20il=20response=20del=20server=20pu=C3=B2=20essere?= =?UTF-8?q?=20in=20JSON=20oppure=20no.=20Il=20client=20spacchetta=20il=20J?= =?UTF-8?q?SON=20se=20c'=C3=A8=20il=20content-type=20giusto.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- api/exceptions/ApiException.js | 5 +++++ api/router.js | 24 +++++++++++------------- frontend/src/modules/api.js | 16 +++++++++++----- frontend/src/modules/engine.js | 1 - 4 files changed, 27 insertions(+), 19 deletions(-) diff --git a/api/exceptions/ApiException.js b/api/exceptions/ApiException.js index af82cad6..24e592b5 100644 --- a/api/exceptions/ApiException.js +++ b/api/exceptions/ApiException.js @@ -47,6 +47,11 @@ function apiErrors(err, req, res, next) { issues: err.issues }) } else { + err.message = JSON.stringify({ + code: err?.code, + message: err.message, + issues: [] + }); next(err); } } diff --git a/api/router.js b/api/router.js index 1edb642c..c583f4a3 100644 --- a/api/router.js +++ b/api/router.js @@ -24,11 +24,7 @@ function response_envelope(controller) { return async function(req, res, next) { try { const data = await controller(req); - res.json({ - code: 200, - message: 'OK', - data: data - }) + res.json(data) } catch(e) { next(e); } @@ -65,16 +61,18 @@ router.post('/login', function(req, res) { res.send({data: { user }}) }) +async function loginController(req) { + const user = req.user.toObject() + console.log(`login/password: ${user.username}`) + + // return user as if it was fetched from /users/:id + const gotUser = await UserController.view({params: {id: `${user._id}`}}) + return {user: gotUser} +} + router.post('/login/password', passport.authenticate('local'), - async function(req, res) { - const user = req.user.toObject() - console.log(`login/password: ${user.username}`) - - // return user as if it was fetched from /users/:id - const gotUser = await UserController.view({params: {id: `${user._id}`}}) - res.send({data: {user: gotUser}}) -}) + response_envelope(loginController)) if (process.env.OAUTH2_CLIENT_ID) { router.get('/login/oauth2', passport.authenticate('oauth2')) diff --git a/frontend/src/modules/api.js b/frontend/src/modules/api.js index 9de35973..74e27838 100644 --- a/frontend/src/modules/api.js +++ b/frontend/src/modules/api.js @@ -29,8 +29,14 @@ class BaseRestClient { headers: headers, body: body }); - if (response.status >= 200 && response.status < 300) { + const contentType = response.headers.get('Content-Type') + if (contentType && contentType.split(';')[0] === 'application/json') { response = await response.json() + } else { + response = { + code: response.status, + message: response.statusText, + } } } catch(err) { response = { @@ -81,7 +87,7 @@ class ApiError extends Error { constructor(res, uri, method, data) { super(`${res.statusText} [${res.status}]`); this.name = "ApiError"; - this.code = res.status; + this.code = res.code; this.issues = res.issues; this.uri = uri; this.method = method; @@ -107,11 +113,11 @@ class RestClient extends BaseRestClient { // genera errori casuali per testarne la gestione if (false && Math.random()>0.8) throw new ApiError({code:500, message: `fake random error! [${method} ${uri}]`}); const res = await super.fetch(uri, method, data, multipart); - - if (res.status < 200 || res.status >= 300) { + console.log(`fetch ${method} ${uri} ${JSON.stringify(data)} => ${JSON.stringify(res)}`) + if (res.code < 200 || res.code >= 300) { throw new ApiError(res, uri, method, data); } - return res.data; + return res; } } diff --git a/frontend/src/modules/engine.js b/frontend/src/modules/engine.js index 31b2b197..5f9b4523 100644 --- a/frontend/src/modules/engine.js +++ b/frontend/src/modules/engine.js @@ -181,7 +181,6 @@ export function useCreateEngine() { try { const res = await api.post('login/password', {username, password}) let { user } = res - console.log(`user: ${JSON.stringify(user)}`) setState(s => ({...s, user})) } catch(err) { // err is ApiError