Using Remult in Non-Remult Routes
When using the CRUD api or BackendMethods, remult
is automatically available. Still, there are many use cases where you may want to user remult in your own routes or other code without using BackendMethods
but would still want to take advantage of Remult
as an ORM and use it to check for user validity, etc...
If you tried to use the remult
object, you may have got the error:
Error: remult object was requested outside of a valid context, try running it within initApi or a remult request cycle
Here's how you can use remult in this context, according to the server you're using:
withRemult middleware
You can use remult as an express middleware for a specific route, using api.withRemult
ts
app.post('/api/customSetAll', api.withRemult, async (req, res) => {
// ....
})
Or as an express middleware for multiple routes
ts
app.use(api.withRemult)
app.post('/api/customSetAll', async (req, res) => {
// ....
})
withRemultAsync promise wrapper
Use the api.withRemultAsync
method in promises
ts
import express from 'express'
import { remultExpress } from 'remult/remult-express'
const app = express();
...
const api = remultExpress({
entities:[Task]
})
app.post('/api/customSetAll', async (req, res) => {
// use remult in a specific piece of code
await api.withRemultAsync(req, async ()=> {
if (!remult.authenticated()) {
res.sendStatus(403);
return;
}
if (!remult.isAllowed("admin")) {
res.sendStatus(403);
return;
}
const taskRepo = remult.repo(Task);
for (const task of await taskRepo.find()) {
task.completed = req.body.completed;
await taskRepo.save(task);
}
res.send();
})
});
You can also use it without sending the request object, for non request related code
ts
setInterval(async () => {
api.withRemultAsync(undefined, async () => {
// ....
})
}, 10000)