@xtr-dev/zod-rpc
Version:
Simple, type-safe RPC library with Zod validation and automatic TypeScript inference
83 lines • 2.74 kB
JavaScript
/**
* Define a new RPC service with typed methods.
*
* @param id - Unique identifier for the service
* @param methods - Object containing method definitions with input/output Zod schemas
* @returns A service definition that can be used with clients and servers
*
* @example
* ```typescript
* const userService = defineService('user', {
* get: {
* input: z.object({ userId: z.string() }),
* output: z.object({ id: z.string(), name: z.string() })
* }
* });
* ```
* @group Service Definition
*/
export function defineService(id, methods) {
return { id, methods };
}
/**
* Internal utility to convert a ServiceDefinition into MethodContracts.
* Used by the RPC client to create callable methods with proper validation.
*
* @template T - Service methods record type
* @param service - The service definition to convert
* @returns Object mapping method names to their contracts
*
* @example
* ```typescript
* const contracts = createServiceContracts(userService);
* // contracts.get: { id: 'user.get', input: inputSchema, output: outputSchema }
* ```
*
* @group Service Definition
*/
export function createServiceContracts(service) {
const contracts = {};
for (const [methodName, methodDef] of Object.entries(service.methods)) {
contracts[methodName] = {
id: `${service.id}.${methodName}`,
input: methodDef.input,
output: methodDef.output,
};
}
return contracts;
}
/**
* Combine a service definition with its implementation to create executable RPC methods.
* Used internally by RPC servers to register service implementations.
*
* @template T - Service methods record type
* @param service - The service definition with schemas
* @param implementation - The actual implementation functions
* @param targetId - Target identifier for routing messages to this implementation
* @returns Array of executable method definitions
*
* @example
* ```typescript
* const methods = implementService(userService, {
* get: async ({ userId }) => ({ name: `User ${userId}`, email: `user${userId}@example.com` }),
* create: async ({ name, email }) => ({ id: '123', success: true })
* }, 'server');
* ```
*
* @group Service Definition
*/
export function implementService(service, implementation, targetId) {
const methods = [];
for (const [methodName, methodDef] of Object.entries(service.methods)) {
const handler = implementation[methodName];
methods.push({
id: `${service.id}.${methodName}`,
targetId,
input: methodDef.input,
output: methodDef.output,
handler,
});
}
return methods;
}
//# sourceMappingURL=service.js.map