The River client is made available to workers on the context, making it easy to enqueue additional jobs from within a job.
Basic usage
The River client working a job is stored in a value on the context provided to workers. The client can be retrieved from the context (or any contexts derived from it) using the ClientFromContext
helper:
func (w *MyWorker) Work(ctx context.Context, job *river.Job[MyArgs]) error {
client := river.ClientFromContext[pgx.Tx](ctx)
...
}
The type parameter pgx.Tx
corresponds to the generic type parameter of the underlying Client[pgx.Tx]
. When using the database/sql
driver, the type parameter should be *sql.Tx
:
client := river.ClientFromContext[*sql.Tx](ctx)
If ClientFromContext
is called on a context which isn't derived from the work context, it will panic. This situation indicates a programming error so most users will find the panic more convenient, although a non-panicking version is also available:
func (w *MyWorker) Work(ctx context.Context, job *river.Job[MyArgs]) error {
client, err := river.ClientFromContextSafely[pgx.Tx](ctx)
if err != nil {
return fmt.Errorf("error getting client from context: %w", err)
}
...
}