File size: 2,302 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
Contains a list of all the routes used in AdminJS. They are grouped within 2 arrays:
- `assets`
- `routes`
It is used by supported HTTP frameworks to render AdminJS pages. You can also use it to write your
own rendering logic.
### How it looks
This is the structure of the Router - both `assets` and `routes`.
```javascript
{
assets: [{
path: '/frontend/assets/app.min.js',
src: path.join(ASSETS_ROOT, 'scripts/app.min.js'),
}, ...],
routes: [{
method: 'GET',
path: '/resources/{resourceId}',
Controller: ResourcesController,
action: 'index',
}, ...]
}
```
### Create router with authentication logic
To create your router with authentication logic you have to:
* write routes responsible for user authentication
* iterate all `assets` and `routes` and handle them.
The following code is almost an identical copy from @adminjs/express plugin.js file. It shows you
how you can assign all the routes to express framework.
```javascript
const { Router } = require('adminjs')
const { routes, assets } = Router
const router = new express.Router()
// here you can write your authentication logic
routes.forEach((route) => {
// we have to change routes defined in AdminJS from {recordId} to :recordId
const expressPath = route.path.replace(/{/g, ':').replace(/}/g, '')
const handler = async (req, res, next) => {
try {
const currentAdmin = null // you can fetch admin from session,
const controller = new route.Controller({ admin }, currentAdmin)
const { params, query } = req
const method = req.method.toLowerCase()
const payload = {
...(req.fields || {}),
...(req.files || {}),
}
const html = await controller[route.action]({
...req,
params,
query,
payload,
method,
}, res)
if (route.contentType) {
res.set({ 'Content-Type': route.contentType })
}
if (html) {
res.send(html)
}
} catch (e) {
next(e)
}
}
if (route.method === 'GET') {
router.get(expressPath, handler)
}
if (route.method === 'POST') {
router.post(expressPath, handler)
}
})
assets.forEach((asset) => {
router.get(asset.path, async (req, res) => {
res.sendFile(path.resolve(asset.src))
})
})
``` |