Custom Adapter
If you want to use protocols other than HTTP or different frameworks, you can create your own adapter.
To do this, you will need to pass the following properties to the adapter
property:
Param | Description | HTTP analogy |
---|---|---|
getPathname | The path that will be parsed and matched with the file. | /products/123/options/78 |
getMethod | Refers to a specific action. This is used in object type files. | GET , POST , PATCH |
defaultNotFoundHandler | This callback will be invoked when no file is found. |
Example for WebSockets.
- JavaScript
- TypeScript
import { initFileRouter } from 'node-file-router';
const useFileRouter = await initFileRouter({
baseDir: `${__dirname}/api`,
adapter: {
getPathname: incomeMessage => incomeMessage.path,
getMethod: incomeMessage => incomeMessage.action,
defaultNotFoundHandler: (incomeMessage, ws) => ws.send(`${incomeMessage.path} is not found.`)
}
});
import { initFileRouter } from 'node-file-router';
import type { SocketAdapter } from 'node-file-router';
const useFileRouter = await initFileRouter({
baseDir: `${__dirname}/api`,
adapter: <SocketAdapter>{
getPathname: incomeMessage => incomeMessage.path,
getMethod: incomeMessage => incomeMessage.action,
defaultNotFoundHandler: (incomeMessage, ws) => ws.send(`${incomeMessage.path} is not found.`)
}
});
To get a working sample, check out /examples/web-socket in the repository.