Skip to content

Commit

Permalink
Add an example of an event handler
Browse files Browse the repository at this point in the history
  • Loading branch information
igalshilman committed Sep 18, 2023
1 parent c5a2570 commit 43902f3
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 1 deletion.
56 changes: 56 additions & 0 deletions examples/handler_example.ts
Original file line number Diff line number Diff line change
@@ -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<UserProfile> => {
return {
id,
name: (await ctx.get<string>("name")) ?? "",
email: (await ctx.get<string>("email")) ?? "",
};
};

const profile = restate.keyedRouter({
registration: restate.keyedEventHandler(registration),
email: restate.keyedEventHandler(email),
get,
});

// restate server
restate.createServer().bindKeyedRouter("profile", profile).listen(8080);
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down

0 comments on commit 43902f3

Please sign in to comment.