Skip to content

Commit

Permalink
riprogettata comunicazione API con Francesco:
Browse files Browse the repository at this point in the history
* il response del server può essere in JSON oppure no. Il client spacchetta il JSON se c'è il content-type giusto.
  • Loading branch information
paolini committed Aug 31, 2023
1 parent f14e1fc commit de2f5f4
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 19 deletions.
5 changes: 5 additions & 0 deletions api/exceptions/ApiException.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Expand Down
24 changes: 11 additions & 13 deletions api/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down Expand Up @@ -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'))
Expand Down
16 changes: 11 additions & 5 deletions frontend/src/modules/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -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;
Expand All @@ -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;
}
}

Expand Down
1 change: 0 additions & 1 deletion frontend/src/modules/engine.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit de2f5f4

Please sign in to comment.