Skip to content

Commit

Permalink
Improve the example in the README.
Browse files Browse the repository at this point in the history
  • Loading branch information
bojanz committed Aug 22, 2024
1 parent 628c035 commit c445dbc
Showing 1 changed file with 11 additions and 8 deletions.
19 changes: 11 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,19 @@ Failed and completed tasks are not retained in the database.

Add table.sql to your migrations.

Define a task payload and a handler to process it:
Define a task and a handler to process it:
```go
// recalculateStockPayload is the payload for the recalculate stock task.
type recalculateStockPayload struct {
ProductID string `json:"product_id"`
}

func NewRecalculateStockTask(productID string) nanoq.Task {
payload, _ := json.Marshal(recalculateStockPayload{
ProductID: productID,
})
return nanoq.NewTask("recalculate-stock", payload, nanoq.WithTimeout(15*time.Second), nanoq.WithScheduledIn(5 * time.Minute))
}

// This could also be a method on a Handler struct containing dependencies.
func RecalculateStock(logger *slog.Logger) nanoq.Handler {
return func(ctx context.Context, t nanoq.Task) error {
Expand All @@ -54,14 +60,11 @@ Create a task (usually in an HTTP handler):
// Usually provided to the HTTP handler.
queueClient := nanoq.Client(db)

payload, _ := json.Marshal(recalculateStockPayload{
ProductID: "my-product",
})
t := nanoq.NewTask("recalculate-stock", payload, nanoq.WithTimeout(15*time.Second), nanoq.WithScheduledIn(5 * time.Minute))

// The transaction (tx) usually already exists. Otherwise, queueClient.RunTransaction() can be used to start one.
t := NewRecalculateStockTask("my-product")
if err := queueClient.CreateTask(ctx, tx, t); err != nanoq.ErrDuplicateTask {
// Handle error.
// Handle unexpected errors.
// Ignores ErrDuplicateTask because multiple HTTP requests can require the same stock recalculation.
}
```

Expand Down

0 comments on commit c445dbc

Please sign in to comment.