Using createRoute
In Silgi, createRoute
is used to define the path (route) of an API endpoint. Route definitions, when used with your schema (createSchema
) and service (createService
) definitions, make your endpoints more readable and manageable.
Basic Usage
import { createRoute } from 'silgi'
export const getBookByIdRoute = createRoute({
route: '/api/library/books/:id',
})
In this example, a route object representing the /api/library/books/:id
path has been created.
Why Use createRoute?
- Readability: Makes route definitions central and clear.
- Reusability: You can reuse the same route in schemas and services.
- Automation: Routes can be easily scanned by CLI and tools.
What to Do After Adding a Route?
After adding a new route or modifying an existing one, you should run the following command that comes with Silgi CLI to automatically update and link your schemas and services:
pnpm silgi prepare
bun silgi prepare
npm run silgi prepare
yarn silgi prepare
This command scans your route definitions and automatically links the relevant schema and services. This way, you fully benefit from type safety and automation advantages.
Linking Schema and Service with a Route Object
A route object can be used with its corresponding schema and service:
import { createRoute, createSchema, createService } from 'silgi'
import { z } from 'zod'
export const getBookByIdRoute = createRoute({
route: '/api/library/books/:id',
})
export const getBookByIdSchema = createSchema({
path: '/api/library/books/:id',
method: ['GET'],
setup: {
pathParams: z.object({ id: z.string() }),
output: z.object({ id: z.string(), name: z.string() }),
},
})
export const getBookByIdService = createService({
path: `GET:/api/library/books/:id`,
setup: {
handler: async (input) => {
// ...handler code...
}
}
})
Parameterized Route Definitions
Parameters in route definitions are specified with a colon (:param
):
export const getUserRoute = createRoute({
route: '/api/users/:userId',
})
Frequently Asked Questions
- Is route definition mandatory? Yes, route definition is mandatory in Silgi. All structures like
createSchema
,createMiddleware
,createService
are fed through the route, and automatic type inferences are also made through the route definition. By defining the route in a single place, you can use it consistently and safely throughout the entire system.