Working with User Consents

What can I do?

Need the full schema, enum list, or error reference? Jump to Reference or Troubleshooting.


Get all consents for the current user

import { BWellSDK } from '@icanbwell/bwell-sdk-ts';

const sdk = new BWellSDK({ clientKey: 'YOUR_CLIENT_KEY' });
await sdk.initialize();
await sdk.authenticate({ token: 'YOUR_ACCESS_TOKEN' });

// getConsents() returns a BWellQueryResult — data/error are properties, not methods.
const result = await sdk.user.getConsents();

if (result.hasError()) {
  console.error('getConsents failed:', result.error);
  process.exit(1);
}

const entries = Array.isArray(result.data?.entry) ? result.data.entry : [];
const consents = entries.map((e) => e?.resource).filter(Boolean);

console.log(Found ${consents.length} consent(s));
consents.forEach((c) => console.log(c.id, c.status, c.provision?.type));
📘

Notes

  • getConsents() takes no required args. Pass new GetConsentsRequest({ category: 'TOS' }) to filter server-side.
  • The result is a BWellQueryResult, so use result.data and result.error as properties and result.hasError() as a method. There is no .success() here.
  • When the user has no consents, result.data?.entry is null — guard with Array.isArray before mapping.

Create a TOS consent

import { BWellSDK, CreateConsentRequest } from '@icanbwell/bwell-sdk-ts';

const sdk = new BWellSDK({ clientKey: 'YOUR_CLIENT_KEY' });
await sdk.initialize();
await sdk.authenticate({ token: 'YOUR_ACCESS_TOKEN' });

const request = new CreateConsentRequest({
  status: 'ACTIVE',     // required — no SDK-side default
  provision: 'PERMIT',
  category: 'TOS',
});

// createConsent() returns a BWellTransactionResult — use .success(), .data(), .error() as methods.
const result = await sdk.user.createConsent(request);

if (!result.success()) {
  console.error('createConsent failed:', result.error().message);
  process.exit(1);
}

const consent = result.data();
console.log('Consent created:', consent.id, consent.status);
📘

Notes

  • status, provision, and category are all required. The SDK has no default for status.
  • The result is a BWellTransactionResult, so success(), data(), and error() are methods. Calling result.data() on a failure throws; calling result.error() on a success throws.
  • createConsent() returns the Consent resource directly — no Bundle unwrapping needed.

Create a PROA attestation consent

PROA_ATTESTATION is the only category whose SDK validator requires organizationId. Pass the ID of the organization the user is attesting to.

import { BWellSDK, CreateConsentRequest } from '@icanbwell/bwell-sdk-ts';

const sdk = new BWellSDK({ clientKey: 'YOUR_CLIENT_KEY' });
await sdk.initialize();
await sdk.authenticate({ token: 'YOUR_ACCESS_TOKEN' });

const request = new CreateConsentRequest({
  status: 'ACTIVE',
  provision: 'PERMIT',
  category: 'PROA_ATTESTATION',
  organizationId: 'YOUR_ORGANIZATION_ID',
});

const result = await sdk.user.createConsent(request);

if (!result.success()) {
  console.error('PROA consent failed:', result.error().message);
  process.exit(1);
}

console.log('PROA consent created:', result.data().id);
📘

Notes

  • Omit organizationId and you'll get organizationId must be provided when category is PROA_ATTESTATION at request construction time.
  • Pass an empty string and you'll get organizationId cannot be empty.
  • Other categories accept organizationId but don't require it.

Reference

Result type cheat sheet

MethodReturnsHow to read it
sdk.user.getConsents(...)BWellQueryResult<ConsentBundle, BaseManagerError>result.data (property), result.error (property), result.hasError() (method). No .success().
sdk.user.createConsent(...)BWellTransactionResult<Consent, BaseManagerError | ValidationError>result.success(), result.failure(), result.data(), result.error() — all methods. .data() throws on failure; .error() throws on success.

Enums

CategoryCode — full list (uppercase only; the SDK rejects anything not in this list):

COMMUNICATION_PREFERENCES_PHI
DATA_SHARING
HEALTH_CIRCLE_ADOLESCENT
HEALTH_CIRCLE_MINOR
HEALTH_MATCH
IAS_IMPORT_RECORDS
MOBILE_COMMUNICATION_PREFERENCES
PERSONALIZED_HEALTH_OFFERS_AND_ADS
PROA_ATTESTATION
TOS

ConsentStatus: 'ACTIVE', 'DRAFT', 'ENTERED_IN_ERROR', 'INACTIVE', 'PROPOSED', 'REJECTED'.

ConsentProvisionType: 'PERMIT', 'DENY'.

📘

Casing

Inputs are uppercase. Response payloads may come back lowercase (e.g. "active", "permit") — the SDK types these as string | null, not the enum. Normalize case before comparing a response value to an input enum.

CreateConsentRequest fields

FieldRequired?TypeNotes
statusrequiredConsentStatusNo SDK default — pass 'ACTIVE' for a new active consent.
provisionrequiredConsentProvisionType'PERMIT' or 'DENY'.
categoryrequiredCategoryCodeOne of the values above.
organizationIdconditionalstringRequired when category === 'PROA_ATTESTATION'. Cannot be empty. Optional otherwise.

GetConsentsRequest fields
The request object itself is optional. If you pass one, the only field is:

FieldRequired?TypeNotes
categoryrequiredCategoryCodeFilters server-side.

Consent response shape

This is the Consent resource as typed by the SDK (models/user/consent/d/ts). Most fields are nullable.

Field types, in TypeScript terms:

FieldType
idstring
statusstring | null (may be lowercase)
dateTimestring | null
metaMeta | null (versionId, lastUpdated, source, security, tag)
scopeCodeableConcept | null
category(CodeableConcept | null)[] | null
patientReference | null
performer(Reference | null)[] | null
organization(Reference | null)[] | null (populated for PROA_ATTESTATION)
policy(ConsentPolicy | null)[] | null
policyRuleCodeableConcept | null
provisionConsentProvision | null (type: string | null, period: Period | null)
📘

resourceType field

The standard FHIR "resourceType": "Consent" field may appear on the raw GraphQL payload but is not part of the SDK's TypeScript Consent type.

📘

Category coding

A consent record may contain multiple category codings. Do not assume category[0].coding[0] is the human-readable label — search by code instead.

const codings = consent.category?.flatMap((c) => c?.coding ?? []) ?? [];
const tosCoding = codings.find((c) => c?.code === 'tos');

Troubleshooting

Each heading below is the exact error string the SDK or runtime produces. Search this section by copying the message from your console.

TypeError: result.data is not a function
You called getConsents() and then result.data() with parentheses.

Fix: getConsents() returns a BWellQueryResult where data is a property. Use result.data (no parens) and result.hasError() to branch.


TypeError: result.success is not a function
You called getConsents() and then result.success().

Fix: BWellQueryResult has no .success() or .failure() method. Branch on result.hasError() instead. (The .success() / .failure() methods exist on BWellTransactionResult, which is what createConsent() returns.)


Invalid consent status: "..."
You passed a status that isn't one of the documented ConsentStatus values (or omitted it entirely).

Fix: Pass 'ACTIVE', 'DRAFT', 'ENTERED_IN_ERROR', 'INACTIVE', 'PROPOSED', or 'REJECTED'. There is no default — status is required.

Invalid consent provision type: "..."
You passed something other than 'PERMIT' or 'DENY' (most commonly lowercase like 'permit').

Fix: Use uppercase exactly: 'PERMIT' or 'DENY'.


Invalid consent category code: "..."
You passed a category that isn't in the supported CategoryCode list. A common offender is 'DIRECT_IMPORT_RECORDS', which is not a real category.

Fix: Use one of the ten values in the Enums section. If you need a category that isn't listed, check whether your SDK package version is current.


organizationId must be provided when category is PROA_ATTESTATION
You sent a PROA attestation consent without organizationId.

Fix: Pass organizationId set to the organization the user is attesting to.


organizationId cannot be empty
You passed organizationId but the string is empty or whitespace-only.

Fix: Either omit organizationId (for categories that don't require it) or pass a non-empty value.


consent.status is "active" but you sent 'ACTIVE'
Inputs are uppercase enums; response payloads may be lowercase. The SDK types Consent.status as string | null, not the enum.

Fix: Normalize before comparing — consent.status?.toLowerCase() === 'active'. Don't assume returned strings match your input casing.


Cannot read properties of null (reading 'map') on a Bundle's entry
When the user has no consents (or no consents matching the filter), bundle.entry is null, not [].

Fix: Guard before mapping: const entries = Array.isArray(bundle?.entry) ? bundle.entry : [].


Error: Uninitialized
You called a sdk.user.* method before sdk.initialize() resolved successfully.

Fix: Confirm await sdk.initialize() returned a result whose .success() is true. The error is a plain Error with message "Uninitialized" — match on error.message === 'Uninitialized', not instanceof Uninitialized (it's not a custom class).


TypeError: sdk.user.getConsents is not a function
Usually an incorrect import path or a stale build.

Fix: Confirm you're importing from @icanbwell/bwell-sdk-ts and that the installed version exposes UserManager.getConsents. Rebuild after package updates.