ItzNotABug / appexpress

An express.js like framework for Appwrite Functions, enabling super-easy navigation!
Apache License 2.0
33 stars 2 forks source link

[FEATURE REQUEST]: Middleware for a specific route. #38

Open moshOntong-IT opened 1 month ago

moshOntong-IT commented 1 month ago

The package includes the Middleware feature, which currently applies to all routes. However, it would be beneficial if AppExpress could add middleware to specific routes only. Perhaps introducing a next parameter in the middleware function could be also a good idea. For instance, the Express Package utilizes this next parameter:

const express = require('express')
const app = express()

app.use((req, res, next) => {
  console.log('Time:', Date.now())
  next()
})
moshOntong-IT commented 1 month ago

Is it possible to return res.res or any kind of return response within middleware. As of now, we use throw Error() so it will indicate that there are some error on middleware. But can we just return res.send/res.json and etc. Because it is good that we can return a status code of the error. For example, I have a middleware then I want to throw an error that 'No found' so I can use a return res.send("No Found", 404)

ItzNotABug commented 1 month ago

Hey @moshOntong-IT 👋, Thanks for this neat suggestion!


Coming to your next question - Absolutely. Every middleware you register can return values via send, json, etc. and end the process at that time.

You can do something like this -

express.middleware((request, response, log, error) => {
  const { userJwtToken } = req.body; // example token.
  const isDashboard = req.path.includes('/dashboard');

  log(req.path);

  if(isDashboard && !userJwtToken) {
    error("Unauthenticated user tried to access the dashboard!");
    response.send("Not Found", 404); // hiding the dashboard for unauthenticated users.
  }
});
moshOntong-IT commented 1 month ago

Hey @moshOntong-IT 👋, Thanks for this neat suggestion!

Coming to your next question - Absolutely. Every middleware you register can return values via send, json, etc. and end the process at that time.

You can do something like this -

express.middleware((request, response, log, error) => {
  const { userJwtToken } = req.body; // example token.
  const isDashboard = req.path.includes('/dashboard');

  log(req.path);

  if(isDashboard && !userJwtToken) {
    error("Unauthenticated user tried to access the dashboard!");
    response.send("Not Found", 404); // hiding the dashboard for unauthenticated users.
  }
});

If that the case, it will still run the main handler? If then, so it will have additional bandwith cost from appwrite. Because in the main handler I have this transaction with Appwrite databases.

ItzNotABug commented 1 month ago

@moshOntong-IT Once you do a response.send call (as shown above), the request ends there.