@smplcty/auth 0.6.4 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/README.md +187 -201
  2. package/dist/create-session.d.ts +10 -9
  3. package/dist/create-session.d.ts.map +1 -1
  4. package/dist/create-session.js +16 -18
  5. package/dist/create-session.js.map +1 -1
  6. package/dist/errors.d.ts +19 -4
  7. package/dist/errors.d.ts.map +1 -1
  8. package/dist/errors.js +23 -5
  9. package/dist/errors.js.map +1 -1
  10. package/dist/find-user-by-communication-method.d.ts.map +1 -1
  11. package/dist/find-user-by-communication-method.js +4 -0
  12. package/dist/find-user-by-communication-method.js.map +1 -1
  13. package/dist/get-user-role-names.d.ts.map +1 -1
  14. package/dist/get-user-role-names.js +2 -0
  15. package/dist/get-user-role-names.js.map +1 -1
  16. package/dist/index.d.ts +9 -5
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +12 -6
  19. package/dist/index.js.map +1 -1
  20. package/dist/internal/hash-token.d.ts +16 -0
  21. package/dist/internal/hash-token.d.ts.map +1 -0
  22. package/dist/internal/hash-token.js +21 -0
  23. package/dist/internal/hash-token.js.map +1 -0
  24. package/dist/methods/errors.d.ts +23 -0
  25. package/dist/methods/errors.d.ts.map +1 -0
  26. package/dist/methods/errors.js +28 -0
  27. package/dist/methods/errors.js.map +1 -0
  28. package/dist/methods/oidc/index.d.ts +92 -0
  29. package/dist/methods/oidc/index.d.ts.map +1 -0
  30. package/dist/methods/oidc/index.js +104 -0
  31. package/dist/methods/oidc/index.js.map +1 -0
  32. package/dist/methods/router.d.ts +19 -0
  33. package/dist/methods/router.d.ts.map +1 -0
  34. package/dist/methods/router.js +95 -0
  35. package/dist/methods/router.js.map +1 -0
  36. package/dist/methods/twilio/index.d.ts +44 -0
  37. package/dist/methods/twilio/index.d.ts.map +1 -0
  38. package/dist/methods/twilio/index.js +77 -0
  39. package/dist/methods/twilio/index.js.map +1 -0
  40. package/dist/methods/types.d.ts +106 -0
  41. package/dist/methods/types.d.ts.map +1 -0
  42. package/dist/methods/types.js +2 -0
  43. package/dist/methods/types.js.map +1 -0
  44. package/dist/revoke-session.d.ts +20 -15
  45. package/dist/revoke-session.d.ts.map +1 -1
  46. package/dist/revoke-session.js +66 -20
  47. package/dist/revoke-session.js.map +1 -1
  48. package/dist/scope/flat-tenant.d.ts +36 -0
  49. package/dist/scope/flat-tenant.d.ts.map +1 -0
  50. package/dist/scope/flat-tenant.js +60 -0
  51. package/dist/scope/flat-tenant.js.map +1 -0
  52. package/dist/set-helpers.d.ts +44 -53
  53. package/dist/set-helpers.d.ts.map +1 -1
  54. package/dist/set-helpers.js +67 -68
  55. package/dist/set-helpers.js.map +1 -1
  56. package/dist/touch-session.d.ts +13 -0
  57. package/dist/touch-session.d.ts.map +1 -0
  58. package/dist/touch-session.js +28 -0
  59. package/dist/touch-session.js.map +1 -0
  60. package/dist/types.d.ts +59 -18
  61. package/dist/types.d.ts.map +1 -1
  62. package/dist/validate-session.d.ts +15 -14
  63. package/dist/validate-session.d.ts.map +1 -1
  64. package/dist/validate-session.js +28 -27
  65. package/dist/validate-session.js.map +1 -1
  66. package/dist/with-service-context.d.ts +15 -12
  67. package/dist/with-service-context.d.ts.map +1 -1
  68. package/dist/with-service-context.js +34 -30
  69. package/dist/with-service-context.js.map +1 -1
  70. package/dist/with-session.d.ts +22 -16
  71. package/dist/with-session.d.ts.map +1 -1
  72. package/dist/with-session.js +67 -63
  73. package/dist/with-session.js.map +1 -1
  74. package/package.json +33 -2
  75. package/schema/functions/current_user_id.yaml +18 -0
  76. package/schema/functions/resolve_session.yaml +42 -23
  77. package/schema/post/0001-backfill-audit-by.sql +15 -0
  78. package/schema/tables/auth_domains.yaml +43 -0
  79. package/schema/tables/communication_channels.yaml +5 -1
  80. package/schema/tables/dev_otp_enrollments.yaml +1 -0
  81. package/schema/tables/roles.yaml +43 -7
  82. package/schema/tables/sessions.yaml +10 -0
  83. package/schema/tables/tenants.yaml +24 -1
  84. package/schema/tables/user_communication_methods.yaml +5 -1
  85. package/schema/tables/user_roles.yaml +1 -0
  86. package/schema/tables/users.yaml +27 -0
  87. package/dist/with-transaction.d.ts +0 -31
  88. package/dist/with-transaction.d.ts.map +0 -1
  89. package/dist/with-transaction.js +0 -49
  90. package/dist/with-transaction.js.map +0 -1
@@ -2,47 +2,66 @@ name: resolve_session
2
2
  language: plpgsql
3
3
  volatility: stable
4
4
  security: definer
5
- returns: TABLE(user_id integer, expires_at timestamptz, tenant_ids integer[], all_tenants boolean, roles varchar[], has_requested_role boolean)
5
+ # A PURE resolver. Given a session token hash, it returns the session's
6
+ # user, its expiry, the user's selectable roles (split from privileges by
7
+ # roles.is_privilege), and the user's privileges. It takes NO role
8
+ # argument and validates NOTHING — not expiry, not revocation, not role
9
+ # membership. All of that lives in withSession (TS), so this SECURITY
10
+ # DEFINER surface stays a minimal read.
11
+ #
12
+ # roles — selectable mode/persona roles (is_privilege = false)
13
+ # default_role — the role names a NULL roleName falls back to (the first
14
+ # is_default role), or NULL if the user has no default
15
+ # privileges — always-on capability flags (is_privilege = true)
16
+ #
17
+ # Soft-delete aware: a soft-deleted session, communication method, or user
18
+ # is treated as non-existent (excluded), and soft-deleted role assignments /
19
+ # roles are dropped from the aggregates.
20
+ #
21
+ # Returns zero rows when no live session matches the hash (withSession maps
22
+ # that to SessionNotFound). Returns one row with empty arrays when the
23
+ # session exists but the user holds no roles.
24
+ returns: TABLE(user_id integer, expires_at timestamptz, roles text[], default_role text, privileges text[])
6
25
  args:
7
- - name: p_session_id
8
- type: text
9
- - name: p_role_name
26
+ - name: p_token_hash
10
27
  type: text
11
28
  body: |
12
29
  BEGIN
13
30
  RETURN QUERY
14
31
  WITH found_session AS (
15
- SELECT s.session_id, s.expires_at, ucm.user_id
32
+ SELECT s.expires_at, ucm.user_id
16
33
  FROM sessions s
17
34
  JOIN user_communication_methods ucm
18
35
  ON ucm.user_communication_method_id = s.user_communication_method_id
19
- WHERE s.session_id = p_session_id
36
+ JOIN users u ON u.user_id = ucm.user_id
37
+ WHERE s.session_id = p_token_hash
38
+ AND s.deleted_at IS NULL
39
+ AND ucm.deleted_at IS NULL
40
+ AND u.deleted_at IS NULL
20
41
  ),
21
- user_role_data AS (
22
- SELECT ur.user_id, ur.tenant_id, r.name AS role_name
42
+ role_data AS (
43
+ SELECT DISTINCT r.name::text AS name, r.is_default, r.is_privilege
23
44
  FROM found_session fs
24
- JOIN user_roles ur ON ur.user_id = fs.user_id
25
- JOIN roles r ON r.role_id = ur.role_id
45
+ JOIN user_roles ur ON ur.user_id = fs.user_id AND ur.deleted_at IS NULL
46
+ JOIN roles r ON r.role_id = ur.role_id AND r.deleted_at IS NULL
26
47
  )
27
48
  SELECT
28
49
  fs.user_id,
29
50
  fs.expires_at,
30
51
  COALESCE(
31
- array_agg(DISTINCT urd.tenant_id) FILTER (WHERE urd.tenant_id IS NOT NULL),
32
- '{}'::integer[]
52
+ (SELECT array_agg(rd.name ORDER BY rd.name) FROM role_data rd WHERE NOT rd.is_privilege),
53
+ '{}'::text[]
33
54
  ),
34
- COALESCE(bool_or(urd.tenant_id IS NULL), false),
55
+ (SELECT rd.name FROM role_data rd WHERE NOT rd.is_privilege AND rd.is_default ORDER BY rd.name LIMIT 1),
35
56
  COALESCE(
36
- array_agg(DISTINCT urd.role_name) FILTER (WHERE urd.role_name IS NOT NULL),
57
+ (SELECT array_agg(rd.name ORDER BY rd.name) FROM role_data rd WHERE rd.is_privilege),
37
58
  '{}'::text[]
38
- ),
39
- bool_or(urd.role_name = p_role_name)
40
- FROM found_session fs
41
- LEFT JOIN user_role_data urd ON urd.user_id = fs.user_id
42
- GROUP BY fs.user_id, fs.expires_at;
59
+ )
60
+ FROM found_session fs;
43
61
  END;
44
62
  comment: >
45
- SECURITY DEFINER function for resolving sessions without requiring
46
- RLS GUCs to be set first. Called by withSession so app_user can
47
- look up session → user → roles through RLS-protected tables.
48
- Returns aggregate role/tenant info only — does not expose raw PII.
63
+ SECURITY DEFINER pure resolver for sessions — bypasses RLS on auth
64
+ tables so app_user can read session → user → roles without GUCs set
65
+ first. Returns aggregate role/privilege info only (no raw PII); does
66
+ no validation (expiry, revocation, and role selection live in
67
+ withSession).
@@ -0,0 +1,15 @@
1
+ -- Bootstrap audit attribution for rows seeded during the migration.
2
+ --
3
+ -- The audit mixin (from @smplcty/schema-std) makes created_by/updated_by
4
+ -- NOT NULL, stamped from app.actor_id. But rows seeded *during* a schema-flow
5
+ -- run have no request actor, so they land with NULL _by — and schema-flow
6
+ -- seeds tables in dependency order that doesn't account for the audit FK, so
7
+ -- we can't simply pre-set the actor (a table may be seeded before app-init
8
+ -- exists). Instead we let the seeds land NULL and back-fill here: post-scripts
9
+ -- run after seeds but before the NOT NULL tighten phase.
10
+ --
11
+ -- audit_backfill_by (shipped by @smplcty/schema-std) fills every NULL
12
+ -- created_by/updated_by on every audit-mixin table in this schema, attributing
13
+ -- them to the app-init service principal. app-init's own row resolves the
14
+ -- self-reference (created_by = its own user_id).
15
+ SELECT audit_backfill_by((SELECT user_id FROM users WHERE name = 'app-init' AND kind = 'service'));
@@ -0,0 +1,43 @@
1
+ table: auth_domains
2
+ # Org-bound sign-in federation config: a tenant's IdP(s). A tenant has 0..N
3
+ # of these (1:N) — mergers, mixed workforces, and multi-domain orgs legitimately
4
+ # have more than one. The method router resolves sub-domain → tenant → its
5
+ # auth_domains: exactly one ⇒ straight redirect; several ⇒ the app shows a
6
+ # chooser (one button per row, labeled display_name, valued by auth_domain_id).
7
+ #
8
+ # This is SIGN-IN federation only. Tenant CRM data connections
9
+ # (HubSpot/Salesforce sync, etc.) are a separate, app-owned concern and
10
+ # do NOT live here. Even for the same vendor, "log in with Salesforce"
11
+ # (a row here) and "connect our Salesforce data" are distinct configs.
12
+ #
13
+ # Absorbed from @smplcty/oidc by the own-domain rule: auth_domains is
14
+ # auth's data model, so auth ships it. Rows are configured at runtime
15
+ # (admin UI) and resolved by auth_domain_id — there is no stable text key.
16
+ mixins: [audit, soft_delete]
17
+ columns:
18
+ - name: auth_domain_id
19
+ type: serial
20
+ primary_key: true
21
+ - name: tenant_id
22
+ type: integer
23
+ nullable: false
24
+ references:
25
+ table: tenants
26
+ column: tenant_id
27
+ # Human label for the sign-in button when a tenant has more than one IdP
28
+ # (e.g. "Microsoft", "Google Workspace").
29
+ - name: display_name
30
+ type: text
31
+ nullable: false
32
+ # 'oidc' | 'saml' | … — selects the MethodHandler. The library only
33
+ # interprets values it ships a handler for; unknown values are an
34
+ # app concern.
35
+ - name: integration_type
36
+ type: text
37
+ nullable: false
38
+ # Provider config + provisioning policy (issuer, clientId, redirect URI,
39
+ # default roles to grant on auto-provision, …). Shape is handler-specific.
40
+ - name: integration_params
41
+ type: jsonb
42
+ nullable: false
43
+ default: "'{}'::jsonb"
@@ -1,4 +1,5 @@
1
1
  table: communication_channels
2
+ mixins: [soft_delete]
2
3
  columns:
3
4
  - name: communication_channel_id
4
5
  type: serial
@@ -6,6 +7,9 @@ columns:
6
7
  - name: name
7
8
  type: text
8
9
  nullable: false
9
- unique_constraints:
10
+ indexes:
11
+ # Partial so a name can be reused after the row is soft-deleted.
10
12
  - columns: [name]
13
+ unique: true
14
+ where: 'deleted_at IS NULL'
11
15
  name: communication_channels_name_key
@@ -1,4 +1,5 @@
1
1
  table: dev_otp_enrollments
2
+ mixins: [soft_delete]
2
3
  columns:
3
4
  # The user_communication_method this enrollment is for. There can only
4
5
  # be one dev OTP enrollment per communication method (PK + FK).
@@ -1,19 +1,43 @@
1
1
  table: roles
2
+ mixins: [audit, soft_delete]
2
3
  columns:
3
4
  - name: role_id
4
5
  type: serial
5
6
  primary_key: true
6
7
  - name: name
7
- type: varchar(30)
8
+ type: varchar(50)
8
9
  nullable: false
9
- unique_constraints:
10
+ # Human-friendly label for UI (role switcher, admin screens).
11
+ - name: display_name
12
+ type: text
13
+ - name: description
14
+ type: text
15
+ # The role auto-selected by withSession when no roleName is requested.
16
+ # An app should mark exactly one is_privilege=false role as default;
17
+ # the library just picks the first default it finds.
18
+ - name: is_default
19
+ type: boolean
20
+ nullable: false
21
+ default: false
22
+ # is_privilege=false → a selectable mode/persona role. These drive the
23
+ # role switcher and become app.active_role for the request.
24
+ # is_privilege=true → an always-on capability flag. These are never
25
+ # "selected"; every privilege the user holds is exported in
26
+ # app.privileges for the request.
27
+ - name: is_privilege
28
+ type: boolean
29
+ nullable: false
30
+ default: false
31
+ indexes:
32
+ # Partial so a role name can be reused after the row is soft-deleted.
10
33
  - columns: [name]
34
+ unique: true
35
+ where: 'deleted_at IS NULL'
11
36
  name: roles_name_key
12
- # The canonical role names @smplcty/auth's withSession() validates against.
13
- #
14
- # IDs 1-3 are reserved for these standard roles. Consumers adding their
15
- # own roles should use IDs >= 100 to avoid colliding with future
16
- # standard-role additions. The library never references these IDs
37
+ # The canonical role names shipped with @smplcty/auth. IDs 1-3 are
38
+ # reserved for these standard mode roles. Consumers adding their own
39
+ # roles (or privileges) should use IDs >= 100 to avoid colliding with
40
+ # future standard-role additions. The library never references these IDs
17
41
  # directly — it always looks up by name — so the IDs are just a stable
18
42
  # convention for migration-time conflict detection.
19
43
  #
@@ -22,8 +46,20 @@ unique_constraints:
22
46
  seeds:
23
47
  - role_id: 1
24
48
  name: 'user'
49
+ display_name: 'User'
50
+ description: 'Standard signed-in user.'
51
+ is_default: true
52
+ is_privilege: false
25
53
  - role_id: 2
26
54
  name: 'settings'
55
+ display_name: 'Settings'
56
+ description: 'Account and organisation settings access.'
57
+ is_default: false
58
+ is_privilege: false
27
59
  - role_id: 3
28
60
  name: 'security'
61
+ display_name: 'Security'
62
+ description: 'Security administration.'
63
+ is_default: false
64
+ is_privilege: false
29
65
  seeds_on_conflict: 'DO NOTHING'
@@ -1,4 +1,10 @@
1
1
  table: sessions
2
+ # soft_delete adds deleted_at. A session is invalid when EITHER expires_at
3
+ # has passed (revokeSession sets it to now()) OR deleted_at is set — the app
4
+ # sets deleted_at to "forget" a session/device. resolve_session and
5
+ # validateSession honor both; the library ships no delete setter (it's a
6
+ # plain column write the app owns).
7
+ mixins: [soft_delete]
2
8
  columns:
3
9
  - name: session_id
4
10
  type: text
@@ -16,6 +22,10 @@ columns:
16
22
  - name: expires_at
17
23
  type: timestamptz
18
24
  nullable: false
25
+ # Updated by touchSession on activity. Powers the "track activity"
26
+ # requirement — distinct from created_at (sign-in time).
27
+ - name: last_seen_at
28
+ type: timestamptz
19
29
  - name: ip
20
30
  type: text
21
31
  - name: city
@@ -1,4 +1,5 @@
1
1
  table: tenants
2
+ mixins: [audit, soft_delete]
2
3
  columns:
3
4
  - name: tenant_id
4
5
  type: serial
@@ -6,6 +7,28 @@ columns:
6
7
  - name: name
7
8
  type: text
8
9
  nullable: false
9
- unique_constraints:
10
+ # Sub-domain / URL slug, e.g. "acme" in acme.app.com. The app parses the
11
+ # request Host to this slug; the method router resolves slug → tenant →
12
+ # its auth_domains, so OIDC sign-in needs no "which org are you?" form.
13
+ # Nullable: multitenancy (and sub-domains) are optional for simple apps.
14
+ - name: slug
15
+ type: text
16
+ # Whether user-bound OTP (Twilio) sign-in is allowed for this tenant.
17
+ # Irrelevant when the tenant has no auth_domain (OTP is the only way);
18
+ # set false to enforce SSO-only on a tenant that has OIDC. Enforced in the
19
+ # router, not just the UI.
20
+ - name: allow_otp
21
+ type: boolean
22
+ nullable: false
23
+ default: true
24
+ indexes:
25
+ # Partial so a tenant name can be reused after the row is soft-deleted.
10
26
  - columns: [name]
27
+ unique: true
28
+ where: 'deleted_at IS NULL'
11
29
  name: tenants_name_key
30
+ # Sub-domain slug is unique among live tenants.
31
+ - columns: [slug]
32
+ unique: true
33
+ where: 'deleted_at IS NULL'
34
+ name: tenants_slug_key
@@ -1,4 +1,5 @@
1
1
  table: user_communication_methods
2
+ mixins: [soft_delete]
2
3
  columns:
3
4
  - name: user_communication_method_id
4
5
  type: serial
@@ -18,6 +19,9 @@ columns:
18
19
  - name: code
19
20
  type: text
20
21
  nullable: false
21
- unique_constraints:
22
+ indexes:
23
+ # Partial so a (channel, code) can be reused after the row is soft-deleted.
22
24
  - columns: [communication_channel_id, code]
25
+ unique: true
26
+ where: 'deleted_at IS NULL'
23
27
  name: user_communication_methods_channel_code_key
@@ -1,4 +1,5 @@
1
1
  table: user_roles
2
+ mixins: [audit, soft_delete]
2
3
  columns:
3
4
  - name: user_role_id
4
5
  type: serial
@@ -1,7 +1,34 @@
1
1
  table: users
2
+ # Auditable. The `audit` mixin is consumed from @smplcty/schema-std and adds
3
+ # created_at / updated_at / created_by / updated_by (the _by columns FK back
4
+ # to users — a self-reference). The audit triggers stamp created_by/updated_by
5
+ # from app.actor_id, so seeding any user requires an actor: see the app-init
6
+ # seed below + the perTxSqlPath note in schema-flow.config.yaml.
7
+ mixins: [audit, soft_delete]
2
8
  columns:
3
9
  - name: user_id
4
10
  type: serial
5
11
  primary_key: true
6
12
  - name: name
7
13
  type: text
14
+ # 'human' → a person who signs in and holds a session.
15
+ # 'service' → a background principal (ingestion, transform-worker,
16
+ # app-init). Service rows are the actor for background writes so
17
+ # audit attribution (app.actor_id) is never NULL. They never own a
18
+ # session. See withServiceContext.
19
+ - name: kind
20
+ type: text
21
+ nullable: false
22
+ default: "'human'"
23
+ check: "kind IN ('human', 'service')"
24
+ # The bootstrap principal. user_id=1 is the app-init service user: the actor
25
+ # every migration-time seed (this row, the standard roles, any consumer seeds)
26
+ # is attributed to via app.actor_id. It seeds first (users seed before tables
27
+ # that FK to it), and stamps its own created_by=1 (the self-reference resolves
28
+ # because the row exists by the time the FK is checked). Consumers add their
29
+ # own users at user_id >= 2.
30
+ seeds:
31
+ - user_id: 1
32
+ name: 'app-init'
33
+ kind: 'service'
34
+ seeds_on_conflict: 'DO NOTHING'
@@ -1,31 +0,0 @@
1
- import type { Pool, PoolClient } from 'pg';
2
- /**
3
- * Check out a connection from the pool, open a transaction, run `fn`,
4
- * and either COMMIT (on success) or ROLLBACK (on throw). The connection
5
- * is always released back to the pool.
6
- *
7
- * The session variables set inside `fn` via the `set*` helpers from this
8
- * package use transaction scope, so they are discarded automatically when
9
- * this function commits or rolls back. There is no risk of cross-request
10
- * leakage.
11
- *
12
- * This is the lower-level companion to `withSession`. Use it when you
13
- * need to set session variables manually (e.g. when migrating existing
14
- * code that has its own session-extraction logic) and don't want the
15
- * full session-and-role validation that `withSession` performs.
16
- *
17
- * @param pool - The pg connection pool.
18
- * @param fn - Callback that receives the transaction-bound client.
19
- * @returns The value returned by `fn`.
20
- *
21
- * @example
22
- * ```ts
23
- * const result = await withTransaction(pool, async (client) => {
24
- * await setSessionId(client, sessionId);
25
- * await setRoleName(client, 'user');
26
- * return client.query('SELECT * FROM widgets');
27
- * });
28
- * ```
29
- */
30
- export declare function withTransaction<T>(pool: Pool, fn: (client: PoolClient) => Promise<T>): Promise<T>;
31
- //# sourceMappingURL=with-transaction.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"with-transaction.d.ts","sourceRoot":"","sources":["../src/with-transaction.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,IAAI,CAAC;AAE3C;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,wBAAsB,eAAe,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,MAAM,EAAE,UAAU,KAAK,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAiBvG"}
@@ -1,49 +0,0 @@
1
- /**
2
- * Check out a connection from the pool, open a transaction, run `fn`,
3
- * and either COMMIT (on success) or ROLLBACK (on throw). The connection
4
- * is always released back to the pool.
5
- *
6
- * The session variables set inside `fn` via the `set*` helpers from this
7
- * package use transaction scope, so they are discarded automatically when
8
- * this function commits or rolls back. There is no risk of cross-request
9
- * leakage.
10
- *
11
- * This is the lower-level companion to `withSession`. Use it when you
12
- * need to set session variables manually (e.g. when migrating existing
13
- * code that has its own session-extraction logic) and don't want the
14
- * full session-and-role validation that `withSession` performs.
15
- *
16
- * @param pool - The pg connection pool.
17
- * @param fn - Callback that receives the transaction-bound client.
18
- * @returns The value returned by `fn`.
19
- *
20
- * @example
21
- * ```ts
22
- * const result = await withTransaction(pool, async (client) => {
23
- * await setSessionId(client, sessionId);
24
- * await setRoleName(client, 'user');
25
- * return client.query('SELECT * FROM widgets');
26
- * });
27
- * ```
28
- */
29
- export async function withTransaction(pool, fn) {
30
- const client = await pool.connect();
31
- try {
32
- await client.query('BEGIN');
33
- try {
34
- const result = await fn(client);
35
- await client.query('COMMIT');
36
- return result;
37
- }
38
- catch (err) {
39
- await client.query('ROLLBACK').catch(() => {
40
- // Swallow rollback errors so the original error surfaces.
41
- });
42
- throw err;
43
- }
44
- }
45
- finally {
46
- client.release();
47
- }
48
- }
49
- //# sourceMappingURL=with-transaction.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"with-transaction.js","sourceRoot":"","sources":["../src/with-transaction.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CAAI,IAAU,EAAE,EAAsC;IACzF,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,OAAO,EAAE,CAAC;IACpC,IAAI,CAAC;QACH,MAAM,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QAC5B,IAAI,CAAC;YACH,MAAM,MAAM,GAAG,MAAM,EAAE,CAAC,MAAM,CAAC,CAAC;YAChC,MAAM,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;YAC7B,OAAO,MAAM,CAAC;QAChB,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,MAAM,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE;gBACxC,0DAA0D;YAC5D,CAAC,CAAC,CAAC;YACH,MAAM,GAAG,CAAC;QACZ,CAAC;IACH,CAAC;YAAS,CAAC;QACT,MAAM,CAAC,OAAO,EAAE,CAAC;IACnB,CAAC;AACH,CAAC"}