totaljs / framework

Node.js framework
http://www.totaljs.com
Other
4.36k stars 450 forks source link

Schema function called twice in a single request #670

Closed ckpiggy closed 6 years ago

ckpiggy commented 6 years ago

I created an api to send sms

exports.install = function () {
  F.route('/sms-send/{target}', ['post', 'json', '*SMS --> @insert'])
}

I found the schema.insert function was called twice in a single request. But when I test with GETSCHEMA

GETSCHEMA('SMS').insert({phone: '0987654321'}, {target: 'staff'}, (err, obj) => {
      OK(!err, 'expect no error')
      OK(obj && obj.ok, 'expect response')
})

The insert function only called once.

petersirka commented 6 years ago

Have you tested it from Chrome or Opera? Because if the sending takes some time then Chrome performs request again.... Try to simulate it from another script or from another browser..... or please create a small example.

BTW: you can't use json with post flag because post is listening on json and urlencode automatically.

ckpiggy commented 6 years ago

I found it is because I call twice next in my F.onAuthorize delegate

F.onAuthorize = async function (req, res, flags, next) {
  let user
  try {
    const data = decryptToken(req)
    user = await findUserByTokenData(data)
    flags.push(`@${user.role}`)
  } catch (e) {
    next(false)
  } finally {
   next(true, user)
  }
}

If auth failed, next will called in catch block and finally block. But I am also curious about "Will the routes doesn't have authorized flag trigger the authorize delegate?" It seems every route will trigger the delegate and ignore the callback result if the route doesn't have authorized flag

petersirka commented 6 years ago

onAuthorize must be executed every request because the routing depends on it. So it doesn't matter if you have authorize, unauthorize flag or no.

ckpiggy commented 6 years ago

Thank you @petersirka