@platformatic/rpc
v2.16.0
Published
A fastify RPC plugin for typescript applications
Downloads
1,239
Keywords
Readme
Platformatic RPC
Fastify plugin to generate a server RPC api for a Fastify application.
[!WARNING]
Platformatic RPC API is in the experimental stage. The feature is not subject to semantic versioning rules. Non-backward compatible changes or removal may occur in any future release. Use of the feature is not recommended in production environments.
Installation
npm install @platformatic/rpc-cli
npm install --save-dev @platformatic/rpc-cli
Usage
- Register the plugin in your Fastify typescript application. Pass the OpenAPI schema as an option. OpenAPI schema will be automatically generated by the CLI command.
import { join } from 'node:path'
import { readFile } from 'node:fs/promises'
import fastify from 'fastify'
import fastifyRpc from '@platformatic/rpc'
const app = fastify()
app.register(async (app) => {
const openapiSchemaPath = join(__dirname, 'openapi.json')
const openapiSchemaFile = await readFile(openapiSchemaPath, 'utf8')
const openapiSchema = JSON.parse(openapiSchemaFile)
await app.register(fastifyRpc, {
openapi: openapiSchema,
prefix: '/rpc',
})
})
app.listen({ port: 3042 }, (err) => {
if (err) {
console.error(err)
process.exit(1)
}
console.log(`Server listening on http://localhost:3042`)
})
- Define RPC handlers in your Fastify application. An RPC handler is a function that takes an optional options object. All parameters will be passed as properties of the options object.
import { join } from 'node:path'
import { readFile } from 'node:fs/promises'
import fastify from 'fastify'
import fastifyRpc from '@platformatic/rpc'
const app = fastify()
app.register(async (app) => {
const openapiSchemaPath = join(__dirname, 'openapi.json')
const openapiSchemaFile = await readFile(openapiSchemaPath, 'utf8')
const openapiSchema = JSON.parse(openapiSchemaFile)
await app.register(fastifyRpc, {
openapi: openapiSchema,
prefix: '/rpc',
})
app.register(async (app) => {
type User = {
name: string
age: number
}
const users = [
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 25 },
{ name: 'Charlie', age: 35 },
]
app.rpc('getUsers', async (options: { maxAge: number }): Promise<User[]> => {
return users.filter(user => user.age <= options.maxAge)
})
})
})
app.listen({ port: 3042 }, (err) => {
if (err) {
console.error(err)
process.exit(1)
}
console.log(`Server listening on http://localhost:3042`)
})
- Run the CLI command to generate the OpenAPI schema.
npx plt-rpc --ts-config ./tsconfig.json --path ./openapi.json
- Start the Fastify application.
Your RPC handlers are exposed as http routes under the /rpc
prefix. All RPC routes are POST routes.
curl -X POST http://localhost:3042/rpc/getUsers -H 'Content-Type: application/json' -d '{"maxAge": 30}'