This guide outlines integrating ActorKit with PartyKit, focusing on XState for defining state machines and Zod for validating commands and events. It includes configuring ActorKit with dynamic secrets and hostnames for enhanced security and deployment flexibility.
Ensure ActorKit, XState, PartyKit, and Zod are installed:
npm install actor-kit xstate partykit zod
Define the logic and states of your actor system using XState.
// src/stateMachines/todoAppMachine.ts
import { createMachine } from 'xstate';
export const todoAppMachine = createMachine({
id: 'todoApp',
initial: 'inactive',
context: {},
states: {
inactive: { on: { ACTIVATE: 'active' } },
active: {},
},
});
Define Zod schemas to ensure the integrity and structure of the data within your actor system, focusing on commands and events.
// src/schemas/TodoSchemas.ts
import { z } from 'zod';
export const AddUserCommandSchema = z.object({
id: z.string(),
name: z.string(),
});
export const TodoEventSchema = z.object({
type: z.enum(['TODO_ADDED', 'TODO_REMOVED']),
payload: z.any(), // Customize according to your payload structure
});
Configure your ActorKit server class with necessary security and network settings.
// src/actorServers/TodoActorServer.ts
import { createMachineServer } from '@/lib/actor-kit';
import { todoAppMachine } from '@/stateMachines/todoAppMachine';
import { TodoEventSchema, AddUserCommandSchema } from '@/schemas/TodoSchemas';
const config = {
machine: todoAppMachine,
schemas: {
event: TodoEventSchema,
command: AddUserCommandSchema,
},
secret: 'YourSecretHere',
hostname: 'YourHostnameHere',
};
const TodoActorServer = createMachineServer(config);
export default TodoActorServer;
Incorporate your ActorKit server in the PartyKit configuration to manage and instantiate your actor system.
// partykit.json
{
"servers": {
"todo": "./src/actorServers/TodoActorServer.ts"
}
}
Ensure your configuration correctly points to your ActorKit server class for PartyKit to use.
- Explore Further: Dive into ActorKit, PartyKit, XState, and Zod documentation to fully utilize their features.
- Develop and Test: Build your application logic around the configured actor systems. Testing ensures your system behaves as expected.
- Adapt and Expand: As your application evolves, refine your actor systems, state machines, and validation schemas to meet new requirements and features.
Following this guide sets up a solid foundation for integrating ActorKit with PartyKit, leveraging the power of XState and Zod for a robust, scalable, and maintainable backend architecture.