Unverified Commit 05c2fe0b authored by Loren ☺️'s avatar Loren ☺️ Committed by GitHub

Update examples/with-temporal (#33674)

Update `with-temporal` example to latest version of Temporal TS SDK API.

AFAICT, next.js doesn't yet support `type: "module"` in root `package.json`, so I added a nested `package.json` for Temporal.

## Documentation / Examples

- [x] Make sure the linting passes by running `yarn lint`
Co-authored-by: 's avatarBalázs Orbán <18369201+balazsorban44@users.noreply.github.com>
parent 1545af58
...@@ -5,23 +5,39 @@ ...@@ -5,23 +5,39 @@
"build": "next build", "build": "next build",
"start": "next start", "start": "next start",
"type-check": "tsc", "type-check": "tsc",
"build-worker": "tsc --build temporal/src/worker/tsconfig.json", "build:worker": "tsc --build temporal/tsconfig.json",
"build-worker.watch": "tsc --build --watch temporal/src/worker/tsconfig.json", "build:worker.watch": "tsc --build --watch temporal/tsconfig.json",
"start-worker": "nodemon -w temporal/lib/ -x 'node temporal/lib/worker || (sleep 5; touch temporal/lib/worker/index.js)'" "start:worker": "cross-env TS_NODE_PROJECT=\"temporal/tsconfig.json\" node --loader ts-node/esm temporal/src/worker.ts",
"start:worker.watch": "cross-env TS_NODE_PROJECT=\"temporal/tsconfig.json\" nodemon temporal/src/worker.ts"
}, },
"dependencies": { "dependencies": {
"next": "latest", "next": "latest",
"node-fetch": "^3.0.0",
"react": "^17.0.2", "react": "^17.0.2",
"react-dom": "^17.0.2", "react-dom": "^17.0.2",
"temporalio": "^0.3.0" "temporalio": "^0.17.2"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "^7.15.0", "@babel/core": "^7.15.0",
"@tsconfig/node14": "^1.0.0", "@tsconfig/node16": "^1.0.0",
"@types/node": "^12.12.21", "@types/node": "^12.12.21",
"@types/node-fetch": "^3.0.3",
"@types/react": "^17.0.2", "@types/react": "^17.0.2",
"@types/react-dom": "^17.0.1", "@types/react-dom": "^17.0.1",
"@typescript-eslint/eslint-plugin": "^5.3.0",
"@typescript-eslint/parser": "^5.3.0",
"cross-env": "^7.0.3",
"nodemon": "^2.0.12", "nodemon": "^2.0.12",
"typescript": "^4.3.5" "ts-node": "^10.2.1",
"typescript": "^4.4.2"
},
"nodemonConfig": {
"execMap": {
"ts": "node --loader ts-node/esm"
},
"ext": "ts",
"watch": [
"temporal/src"
]
} }
} }
import { NextApiRequest, NextApiResponse } from 'next' import { NextApiRequest, NextApiResponse } from 'next'
import { Connection, WorkflowClient } from '@temporalio/client' import { WorkflowClient } from '@temporalio/client'
import { Order } from '../../../temporal/src/interfaces/workflows' import { order } from '../../../temporal/src/workflows'
export type Data = { export type Data = {
result: string result: string
...@@ -25,11 +25,14 @@ export default async function handler( ...@@ -25,11 +25,14 @@ export default async function handler(
const { itemId, quantity } = JSON.parse(req.body) const { itemId, quantity } = JSON.parse(req.body)
// Connect to our Temporal Server running locally in Docker // Connect to our Temporal Server running locally in Docker
const connection = new Connection() const client = new WorkflowClient()
const client = new WorkflowClient(connection.service)
const example = client.stub<Order>('order', { taskQueue: 'orders' }) // Execute the order Workflow and wait for it to finish
const result = await client.execute(order, {
taskQueue: 'my-nextjs-project',
workflowId: 'my-business-id',
args: [userId, itemId, quantity],
})
// Execute the Order workflow and wait for it to finish
const result = await example.execute(userId, itemId, quantity)
return res.status(200).json({ result }) return res.status(200).json({ result })
} }
import fetch from 'node-fetch'
export type ChargeResult = {
status: string
errorMessage?: string
}
export async function chargeUser(
userId: string,
itemId: string,
quantity: number
): Promise<ChargeResult> {
// TODO send request to the payments service that looks up the user's saved
// payment info and the cost of the item and attempts to charge their payment
// method.
console.log(`Charging user ${userId} for ${quantity} of item ${itemId}`)
try {
const response = await fetch('http://httpbin.org/get?status=success')
const body: any = await response.json()
return { status: body.args.status }
} catch (e: any) {
return { status: 'failure', errorMessage: e.message }
}
}
export async function checkAndDecrementInventory( export async function checkAndDecrementInventory(
itemId: string, itemId: string,
quantity: number quantity: number
...@@ -24,5 +49,6 @@ export async function incrementInventory( ...@@ -24,5 +49,6 @@ export async function incrementInventory(
// { $inc: { numAvailable: quantity } } // { $inc: { numAvailable: quantity } }
// ) // )
// return result.modifiedCount === 1 // return result.modifiedCount === 1
console.log(`Incrementing ${itemId} inventory by ${quantity}`)
return true return true
} }
export type ChargeResult = {
success: boolean
errorMessage?: string
}
export async function chargeUser(
userId: string,
itemId: string,
quantity: number
): Promise<ChargeResult> {
// TODO send request to the payments service that looks up the user's saved
// payment info and the cost of the item and attempts to charge their payment
// method.
console.log(`Charging user ${userId} for ${quantity} of item ${itemId}`)
return { success: true }
// return { success: false, errorMessage: 'Card expired' }
}
{
"extends": "@tsconfig/node14/tsconfig.json",
"version": "4.2.2",
"compilerOptions": {
"emitDecoratorMetadata": false,
"experimentalDecorators": false,
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"composite": true,
"incremental": true,
"rootDir": ".",
"outDir": "../../lib/activities"
},
"include": ["./**/*.ts"],
"references": [
{
"path": "../interfaces/tsconfig.json"
}
]
}
{
"extends": "@tsconfig/node14/tsconfig.json",
"version": "4.2.2",
"compilerOptions": {
"emitDecoratorMetadata": false,
"experimentalDecorators": false,
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"composite": true,
"incremental": true,
"rootDir": ".",
"outDir": "../../lib/interfaces"
},
"include": ["./**/*.ts"]
}
import { Workflow } from '@temporalio/workflow'
export interface Order extends Workflow {
main(userId: string, itemId: string, quantity: number): Promise<string>
}
import { Worker } from '@temporalio/worker'
import { URL } from 'url'
import path from 'path'
import * as activities from './activities.js'
// Support running both complied code and ts-node/esm loader
const workflowsPath = new URL(
`./workflows${path.extname(import.meta.url)}`,
import.meta.url
).pathname
const worker = await Worker.create({
workflowsPath,
activities,
taskQueue: 'my-nextjs-project',
})
await worker.run()
import { Worker } from '@temporalio/worker'
async function run() {
// https://docs.temporal.io/docs/node/workers/
const worker = await Worker.create({
workDir: __dirname,
nodeModulesPath: `${__dirname}/../../../node_modules`,
taskQueue: 'orders',
})
// Start accepting tasks on the `orders` queue
await worker.run()
}
run().catch((err) => {
console.error(err)
process.exit(1)
})
{
"extends": "@tsconfig/node14/tsconfig.json",
"version": "4.2.2",
"compilerOptions": {
"emitDecoratorMetadata": false,
"experimentalDecorators": false,
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"composite": true,
"incremental": true,
"rootDir": ".",
"outDir": "../../lib/worker"
},
"include": ["./**/*.ts"],
"references": [
{
"path": "../interfaces/tsconfig.json"
},
{
"path": "../activities/tsconfig.json"
},
{
"path": "../workflows/tsconfig.json"
}
]
}
import { Order } from '../interfaces/workflows' import { proxyActivities } from '@temporalio/workflow'
import { // Only import the activity types
checkAndDecrementInventory, import type * as activities from './activities.js'
incrementInventory,
} from '@activities/inventory'
import { chargeUser, ChargeResult } from '@activities/payment'
async function main( const { chargeUser, checkAndDecrementInventory, incrementInventory } =
proxyActivities<typeof activities>({
startToCloseTimeout: '1 minute',
})
export async function order(
userId: string, userId: string,
itemId: string, itemId: string,
quantity: number quantity: number
...@@ -15,8 +17,12 @@ async function main( ...@@ -15,8 +17,12 @@ async function main(
quantity quantity
) )
if (haveEnoughInventory) { if (haveEnoughInventory) {
const result: ChargeResult = await chargeUser(userId, itemId, quantity) const result: activities.ChargeResult = await chargeUser(
if (result.success) { userId,
itemId,
quantity
)
if (result.status === 'success') {
return `Order successful!` return `Order successful!`
} else { } else {
await incrementInventory(itemId, quantity) await incrementInventory(itemId, quantity)
...@@ -26,5 +32,3 @@ async function main( ...@@ -26,5 +32,3 @@ async function main(
return `Sorry, we don't have enough items in stock to fulfill your order.` return `Sorry, we don't have enough items in stock to fulfill your order.`
} }
} }
export const workflow: Order = { main }
{
"extends": "@tsconfig/node14/tsconfig.json",
"version": "4.2.2",
"compilerOptions": {
"emitDecoratorMetadata": false,
"experimentalDecorators": false,
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"composite": true,
"incremental": true,
"rootDir": ".",
"lib": [
"es5",
"es2015.core",
"es2015.generator",
"es2015.iterable",
"es2015.promise",
"es2015.proxy",
"es2015.reflect",
"es2015.symbol",
"es2015.symbol.wellknown",
"es2016.array.include",
"es2017.object",
"es2017.intl",
"es2017.sharedmemory",
"es2017.string",
"es2017.typedarrays"
],
"typeRoots": ["."],
"outDir": "../../lib/workflows",
"paths": {
"@activities": ["../activities"],
"@activities/*": ["../activities/*"]
}
},
"include": ["./**/*.ts"],
"references": [
{
"path": "../activities/tsconfig.json"
},
{
"path": "../interfaces/tsconfig.json"
}
]
}
{
"extends": "@tsconfig/node16/tsconfig.json",
"version": "4.4.2",
"compilerOptions": {
"target": "es2017",
"module": "esnext",
"moduleResolution": "node",
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"rootDir": "./src",
"outDir": "./lib"
},
"include": ["src/**/*.ts"]
}
...@@ -12,12 +12,8 @@ ...@@ -12,12 +12,8 @@
"moduleResolution": "node", "moduleResolution": "node",
"resolveJsonModule": true, "resolveJsonModule": true,
"isolatedModules": true, "isolatedModules": true,
"jsx": "preserve", "jsx": "preserve"
"paths": {
"@activities": ["./temporal/src/activities"],
"@activities/*": ["./temporal/src/activities/*"]
}
}, },
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"], "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"] "exclude": ["temporal/"]
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment