diff --git a/examples/handler_example.ts b/examples/handler_example.ts new file mode 100644 index 00000000..7ca5e4f7 --- /dev/null +++ b/examples/handler_example.ts @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2023 - Restate Software, Inc., Restate GmbH + * + * This file is part of the Restate SDK for Node.js/TypeScript, + * which is released under the MIT license. + * + * You can find a copy of the license in file LICENSE in the root + * directory of this repository or package, or at + * https://github.com/restatedev/sdk-typescript/blob/main/LICENSE + */ + +/* eslint-disable no-console */ + +/* + * A simple example program using the Restate's event handlers. + */ + +import * as restate from "../src/public_api"; + +const registration = async (ctx: restate.RpcContext, event: restate.Event) => { + // store in state the user's information as coming from the registeration event + const { name } = event.json<{ name: string }>(); + ctx.set("name", name); +}; + +const email = async (ctx: restate.RpcContext, event: restate.Event) => { + // store in state the user's information as coming from the registeration event + const { email } = event.json<{ email: string }>(); + ctx.set("email", email); +}; + +type UserProfile = { + id: string; + name: string; + email: string; +}; + +const get = async ( + ctx: restate.RpcContext, + id: string +): Promise => { + return { + id, + name: (await ctx.get("name")) ?? "", + email: (await ctx.get("email")) ?? "", + }; +}; + +const profile = restate.keyedRouter({ + registration: restate.keyedEventHandler(registration), + email: restate.keyedEventHandler(email), + get, +}); + +// restate server +restate.createServer().bindKeyedRouter("profile", profile).listen(8080); diff --git a/package.json b/package.json index 09133ac5..e909e39c 100644 --- a/package.json +++ b/package.json @@ -38,7 +38,8 @@ "verify": "npm run format -- --check && npm run test && npm run lint && npm run build", "release": "release-it", "example": "RESTATE_DEBUG_LOGGING=JOURNAL ts-node-dev --respawn --transpile-only ./examples/example.ts", - "grpcexample": "RESTATE_DEBUG_LOGGING=JOURNAL ts-node-dev --respawn --transpile-only ./examples/grpc_example.ts" + "grpcexample": "RESTATE_DEBUG_LOGGING=JOURNAL ts-node-dev --respawn --transpile-only ./examples/grpc_example.ts", + "handlerexample": "RESTATE_DEBUG_LOGGING=JOURNAL ts-node-dev --respawn --transpile-only ./examples/handler_example.ts" }, "files": [ "dist"