@seibert/typed-forge-bridge
v1.0.0
Published
A small TypeScript library which introduces end-to-end type-safety into your Atlassian Forge Apps
Downloads
38
Readme
typed-forge-bridge
A small TypeScript library which introduces end-to-end type-safety into your Atlassian Forge Apps!
Usage
Centrally define what the API of your FaaS backend is supposed to look like:
// types.ts
import { ForgeEndpoint } from "@seibert/typed-forge-bridge";
type User = {
id: string,
name: string,
email: string,
};
type GetUserParams = {
id: string,
};
type CreateUserParams = {
name: string,
email: string,
};
export const apiDefinition = {
getUser: new ForgeEndpoint<GetUserParams, User>(),
createUser: new ForgeEndpoint<CreateUserParams, void>(),
};
We can now use this definition to infer the types of the resolver's handler functions.
// index.ts
import Resolver from "@forge/resolver";
import { define } from "@seibert/typed-forge-bridge";
import { apiDefinition } from "@shared/types";
const resolver = new Resolver();
// TypeScript ensures that this object implements all the endpoints defined
// in apiDefinition
define<typeof apiDefinition>(resolver, {
// TypeScript can infer that payload is of type GetUserParams and this
// function is expected to return a User
getUser: async ({ payload, context }) => {
// retrieve user ...
return user;
},
// TypeScript can infer that payload is of type CreateUserParams and this
// function is expected to return void
createUser: async ({ payload }) => {
// create user ...
}
});
export const handler = resolver.getDefinitions();
And on the client-side we can infer a fully typed API client for the FaaS backend.
// CreateUserButton.tsx
import { invoke } from "@forge/bridge";
import { buildClient } from "@seibert/typed-forge-bridge";
import { apiDefinition } from "@shared/types";
// this client now has a method for each endpoint defined in apiDefinition
export const bridgeClient = buildClient(apiDefinition, invoke);
function CreateUserButton() {
return <button
onClick={ async () => {
// the method createUser expects CreateUserParams and returns void as
// defined in apiDefinition
await bridgeClient.createUser({
name: "Max Mustermann",
email: "[email protected]",
});
} }
>
create user
</button>;
}