Skip to content

Using createService

In Silgi, createService is used to define the business logic and handler function of an API endpoint. Each service is associated with a route and schema and is the main function that responds to incoming requests.

Basic Usage

typescript
import { 
createError
,
createService
} from 'silgi'
export const
getBookByIdService
=
createService
({
path
: 'GET:/api/library/books/:id',
setup
: {
handler
: async (
input
,
shared
) => {
// Your business logic here const
bookId
=
input
.
parameters
.
path
?.
id
if (!
bookId
) {
throw
createError
({
statusCode
: 400,
message
: 'Book ID is required'
}) } return {
id
:
bookId
,
name
: 'Sample Book',
} } } })

Parameters

  • path: Specifies the route and HTTP method the service will listen to. (e.g., 'GET:/api/library/books/:id')
  • setup: The main configuration object for the service, consisting of the following fields:
    • handler: The function containing the main business logic of the service. (Required)
    • rules: Service-specific router settings (e.g., access rules, rate limits, etc.).
    • modules: An object containing additional settings from modules (e.g., auth, metrics, logger module configurations).
    • storage: unstorage backed universal key-value storage. Provides a unified key-value storage API that can work with 20+ different drivers. You can access it in the service handler with shared.storage.

Handler Function

The handler function processes the incoming request and returns the response. The handler's signature is:

typescript
(
  input: ServiceHandlerInput<Schema, Route, HiddenParameters>,
  shared?: SilgiRuntimeShareds,
  event?: SilgiEvent,
  source?: ServiceHandlerSource<Schema, Route>
) => Promise<any>

Parameters:

  • input: Contains parameters from the request such as path, query, and body.
  • shared: Provides access to shared helper functions and infrastructure tools.
  • event: Contains framework or infrastructure events related to the request. Provides access to properties like event.req and event.res.
  • source: (Optional) The source or additional metadata from which the handler was called. You can use this for modules like graphql.

Advanced Usage

  • Shared Helpers: You can access common functions within the handler using shared.
  • Error Handling: You can throw meaningful errors with createError.
  • Type Safety: Automatic type inference is performed with route and schema.

Example: Usage with Shared Helper

typescript
import { createError, createService } from 'silgi'

export const getBookByIdService = createService({
  path: 'GET:/api/library/books/:id',
  setup: {
    handler: async (input, shared, event, source) => {
      const bookId = input.parameters.path?.id
      if (!bookId) {
        throw createError({
          statusCode: 400,
          message: 'Book ID is required'
        })
      }
      // Usage of shared helper
      const name = shared.formatBookName('Sample Book')
      return {
        id: bookId,
        name,
      }
    }
  }
})

Frequently Asked Questions

  • What parameters are available in a service? The input and shared parameters are automatically passed to the handler function.

  • Are services automatically linked to routes and schemas? Yes, when you run the pnpm silgi prepare command with your route and schema definitions, services are automatically linked, and type safety is ensured.


Released under the MIT License. (dev). Documentation design is a copy of vite.dev docs.