npm package: @impartner/angular-sdk
Description: This package contains [Angular](https://angular.io/) services and typings to facilitate development and integration of Angular web components written for Impartner host applications.
Author: Impartner
Latest version: 4.0.0

# `@impartner/angular-sdk`

This package contains [Angular](https://angular.io/) services and typings to facilitate development and integration of Angular web components written for Impartner host applications.

## Dependencies

Each release of this library targets for a specific minimum version of Angular. Please refer to the below table to see which versions are supported or targeted for a given release.

| @impartner/angular-sdk | Angular  |
| ---------------------- | -------- |
| 1.1.0                  | ^14.2.0  |
| 2.0.0                  | >=17.0.4 |
| 3.0.0                  | >=18.2.0 |
| 4.0.0                  | >=20.2.4 |

## Getting Started

1. Add the `@impartner/angular-sdk` dependency from npm.
2. Update the application project's `environment.ts` and `environment.prod.ts` files to include the `impartnerEndpointUrl` property.
   - In `environment.ts`, set this property value to `"/api"`, or some other unique path segment that will be used in the same project's local-serve proxy configuration to proxy requests to the Impartner PRM.
   - In `environment.prod.ts`, set this property value to an empty string, as it will not be used in production builds.
3. Import `ImpartnerSdkModule` to the application's **root NgModule** using the `ImpartnerSdkModule.forRoot(...)` static function, passing the project's `environment` constant as the only argument.

   ```typescript
   import { ImpartnerSdkModule } from '@impartner/angular-sdk';

   @NgModule({
     ...
     imports: [
       ...
       ImpartnerSdkModule.forRoot(environment),
       ...
     ],
     ...
   })
   export class AppModule { ... }
   ```

## Available Services

This package provides several discrete services to enable integration with Impartner's front-end client applications, and does so through normal Angular dependency injection.

- [ImpartnerConfigService](#impartnerconfigservice)
- [ImpartnerEventBusService](#impartnereventbusservice)
- [ImpartnerMetadataService](#impartnermetadataservice)
- [ImpartnerObjectService](#impartnerobjectservice)
- [ImpartnerUserService](#impartneruserservice)
- [IImpartnerHttpClient](#iimpartnerhttpclient)
- [IImpartnerRouter](#iimpartnerrouter)
- [IImpartnerLogger](#iimpartnerlogger)
- [OrchestrationStudioService](#orchestrationstudioservice)

### ImpartnerConfigService

| Service Type             | DI Token                 | Provided In |
| ------------------------ | ------------------------ | ----------- |
| `ImpartnerConfigService` | `ImpartnerConfigService` | root        |

A simple service for synchronously fetching current configuration and context information that may be pertinent to client widget or micro front-end.

#### Methods

| Name        |                                                                                                                                                                                              |
| ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `getConfig` | `getConfig() => IImpartnerConfig`<br/>Returns current configuration and context for the client application, including rendered locale, available locales, available features, and tenant ID. |

### ImpartnerEventBusService

| Service Type               | DI Token                   | Provided In |
| -------------------------- | -------------------------- | ----------- |
| `ImpartnerEventBusService` | `ImpartnerEventBusService` | root        |

A service for emitting and listening to events available to the Impartner client application and any other widgets or micro front-ends in scope.

#### Methods

| Name     |                                                                                                                                                               |
| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `emit`   | `emit<T>(eventName: string, event: T) => void`<br/>Synchronously emits a new bus event for `eventName` with the provided payload `event` of generic type `T`. |
| `event$` | `event$<T>(eventName: string) => Observable<T>`<br/>Returns a hot Observable for bus events with name `eventName`.                                            |

### ImpartnerMetadataService

| Service Type               | DI Token                   | Provided In |
| -------------------------- | -------------------------- | ----------- |
| `ImpartnerMetadataService` | `ImpartnerMetadataService` | root        |

A service for fetching metadata about Impartner PRM objects and/or their fields from the host.

#### Methods

| Name                       |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `describeAllObjects`       | `describeAllObjects(profile?: DescribeProfile, context?: DescribeContextTypes) => Observable<IPrmObjectDefinition[]>` <br/> Asynchronously fetches object metadata for all Impartner PRM objects visible to the user type specified by `profile`, or for the current user if unspecified. The `context` parameter determines how much information is provided, `All` and `Sync` options return basic information (eg. display name, API name, CRUD capabilities), `Extended` returns in-depth object metadata in the form of the `ExtendedObjectProperties` interface.                                                                                                                                                              |
| `describeObject`           | `describeObject(prmObjectName: string, profile?: DescribeProfile) => Observable<IPrmObjectDefinition \| null>` <br/> Asynchronously fetches basic object metadata for Impartner PRM object `prmObjectName` for user type specified by `profile`, or for the current user if unspecified. Result may be `null` if the named Impartner PRM object does not exist or if it is inaccessible to the user type.                                                                                                                                                                                                                                                                                                                           |
| `describeFields`           | `describeFields(prmObjectName: string, profile?: DescribeProfile, context?: DescribeContextTypes, depth?: number) => Observable<IPrmFieldDefinition[]>` <br/> Asynchronously fetches field metadata for all fields of Impartner PRM object `prmObjectName` for user type specified by `profile`, or for the current user if unspecified. The `context` parameter determines how much information is provided, `All` and `Sync` options return basic information, `Extended` returns in-depth field metadata in the form of the `ExtendedFieldProperties` interface. The `depth` parameter will recursively populate the `foreignFieldDefinitions` array for fields with a `fieldType` of `fk`.                                      |
| `describeField`            | `describeField(prmObjectName: string, fieldName: string, profile?: DescribeProfile, context?: DescribeContextTypes, depth?: number) => Observable<IPrmFieldDefinition \| null>` <br/> Asynchronously fetches field metadata for named field `fieldName` of Impartner PRM object `prmObjectName` for user type specified by `profile`, or for the current user if unspecified. The `context` parameter determines how much information is provided, `All` and `Sync` options return basic information, `Extended` returns in-depth field metadata in the form of the `ExtendedFieldProperties` interface. The `depth` parameter will recursively populate the `foreignFieldDefinitions` array for fields with a `fieldType` of `fk`. |
| `describeFilterEvaluators` | `describeFilterEvaluators() => Observable<IFilterCriteriaTypeDefinitions>` <br/> Asynchronously fetches the collection of different Impartner PRM object field data types and the filter operator types available for them.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `clearCache`               | `clearCache() => void` <br /> Clears internal cache structures of the service instance.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |

### ImpartnerObjectService

| Service type             | DI Token                 | Provided In |
| ------------------------ | ------------------------ | ----------- |
| `ImpartnerObjectService` | `ImpartnerObjectService` | root        |

A service for performing CRUD operations with Impartner PRM object records.

#### Methods

| Name                |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `get`               | `get<T>(objectName: string, id: number \| string, fields?: string[]) => Observable<IPrmApiResult<T>>` <br/> Asynchronously retrieves a record with the provided `id` of the specified Impartner PRM object type `objectName`, including any fields named in the `fields` array.                                                                                                                                                                                                                                                                                                                                         |
| `getMany`           | `getMany<T>(objectName: string, options?: ISearchOptions) => Observable<IPrmApiResult<IEntitySearchResult<T>>>` <br/> Asynchronously retrieves many records of the specified Impartner PRM object type `objectName`. Providing an `options` value allows for specifying additional aspects of the request, including returned record fields, filter criteria, sort order, and skip/take values for pagination.                                                                                                                                                                                                          |
| `getManyByCriteria` | `getManyByCriteria<T>(objectName: string, options: ICriteriaSearchOptions) => Observable<IPrmApiResult<IEntitySearchResult<T>>>` <br/> Asynchronously retrieves many records of the specified Impartner PRM object type `objectName`. Providing an `options` value allows for specifying additional aspects of the request, including returned record fields, filter criteria, sort order, and skip/take values for pagination. <br/> While similar in nature to `getMany`, the expanded typing of the `options` argument allows for alternative filtering logic and behavior, including integration with custom logic. |
| `create`            | `create<T>(objectName: string, body: Partial<T>) => Observable<IPrmApiResult<T>>` <br/> Asynchronously creates a single new record of the specified Impartner PRM object type `objectName`, setting its field values according to the provided payload in `body`. The returned result will be the created record, including populated auto-ID fields.                                                                                                                                                                                                                                                                   |
| `createMany`        | `createMany<T>(objectName: string, body: Partial<T>[]) => Observable<IPrmBulkApiResult<T>>` <br/> Asynchronously creates one or more new records of the specified Impartner PRM object type `objectName`, setting their field values according to the provided elements for `body`. The returned result will contain an array of the created records, including populated auto-ID fields.                                                                                                                                                                                                                               |
| `update`            | `update<TBody, TResult extends TBody = TBody>(objectName: string, id: number \| string, body: TBody, returnFields?: (string \| keyof TResult)[]) => Observable<IPrmApiResult<TResult>>` <br/> Asynchronously updates a single record with the provided `id` of the specified Impartner PRM object type `objectName`, updating its fields according to the provided values in `body`. The returned results will include the same fields as those present on `body`, as well as any additional fields specified by the `fields` array.                                                                                    |
| `updateMany`        | `updateMany<TResult = unknown>(objectName: string, body: unknown[], returnFields?: (string \| keyof TResult)[]) => Observable<IPrmBulkApiResult<TResult>>` <br/> Asynchronously updates multiple records of the specified Impartner PRM object type `objectName`, updating their fields according to the partial record values in `body`. **Every** record in `body` must have an `id` property present. The returned results will include the same fields as those present on their records in `body`, as well as any additional fields specified by the `fields` array.                                               |
| `delete`            | `delete(objectName: string, id: number \| string) => Observable<IPrmApiResult<{ id: number \| string }>>` <br/> Asynchronously deletes a record with the provided `id` of the specified Impartner PRM object type `objectName`. The result will be a plain object with the ID of the deleted record.                                                                                                                                                                                                                                                                                                                    |
| `deleteMany`        | `deleteMany(objectName: string, ids: (number \| string)[]) => Observable<IPrmBulkApiResult<{ id: number \| string }[]>` <br /> Asynchronously deletes one or more records for the provided `ids` array values of the specified Impartner PRM object type `objectName`. The result will be an array of plain objects with the IDs of the deleted records.                                                                                                                                                                                                                                                                |
| `export`            | `export(objectName: string, criteria: IExportOptions) => Observable<ExportResult>` <br/> Asynchronously retrieves a file export of records of the specified Impartner PRM object type `objectName` according to the file type, headers, filter criteria, and sort order in `criteria`. Result is an `ExportResult` instance that can trigger file download in the browser by invoking the `ExportResult`'s `startDownload()` method.                                                                                                                                                                                    |

### ImpartnerUserService

| Service Type           | DI Token               | Provided In |
| ---------------------- | ---------------------- | ----------- |
| `ImpartnerUserService` | `ImpartnerUserService` | root        |

A service for accessing basic information about the current user.

#### Methods

| Name              |                                                                                                                                            |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `getUser`         | `getUser() => IProfile` <br/> Retrieves the current user's profile, including (but not limited to) id, user type, name, and email address. |
| `getUserSegments` | `getUserSegments() => Observable<IUserSegmentationValues>` <br/> Asynchronously retrieves segmentation information about the current user. |

### IImpartnerHttpClient

| Service Type           | DI Token                      | Provided In                       |
| ---------------------- | ----------------------------- | --------------------------------- |
| `IImpartnerHttpClient` | `IMPARTNER_HTTP_CLIENT_TOKEN` | `ImpartnerSdkModule.forRoot(...)` |

A service for making HTTP calls to the Impartner PRM host. This service ensures that any additional required information (eg. HTTP headers) are present for calls to Impartner. This service should always be used when attempting to make HTTP-based API calls to the Impartner host.

#### Methods

| Name     |                                                                                                                                                                                                                                                                         |
| -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `get`    | `get<T, U extends IApiResultBase = IApiResult<T>>(url: string, options?: IHttpClientOptions) => Promise<U>` <br/> Asynchronously makes an HTTP GET call to the Impartner PRM resource path specified by `url`.                                                          |
| `post`   | `post<T, U extends IApiResultBase = IApiResult<T>>(url: string, body: unknown, options?: IHttpClientOptions) => Promise<U> ` <br/> Asynchronously makes an HTTP POST call to the Impartner PRM resource path specified by `url`, with the `body` value as its payload.  |
| `put`    | `put<T, U extends IApiResultBase = IApiResult<T>>(url: string, body: unknown, options?: IHttpClientOptions) => Promise<U>` <br/> Asynchronously makes an HTTP PUT call to the Impartner PRM resource path specified by `url`, with the `body` value as its payload.     |
| `patch`  | `patch<T, U extends IApiResultBase = IApiResult<T>>(url: string, body: unknown, options?: IHttpClientOptions) => Promise<U>` <br/> Asynchronously makes an HTTP PATCH call to the Impartner PRM resource path specified by `url`, with the `body` value as its payload. |
| `delete` | `delete<T, U extends IApiResultBase = IApiResult<T>>(url: string, body: unknown, options?: IHttpClientOptions) => Promise<U>` <br/> Asynchronously makes an HTTP DELETE call to the Impartner PRM resource path specified by `url`.                                     |

### IImpartnerRouter

| Service Type       | DI Token                 | Provided In                       |
| ------------------ | ------------------------ | --------------------------------- |
| `IImpartnerRouter` | `IMPARTNER_ROUTER_TOKEN` | `ImpartnerSdkModule.forRoot(...)` |

A service for accessing and modifying navigation state within the host Impartner front-end application.

#### Methods

| Name                     |                                                                                                                                                                                                                                 |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `navigate`               | `navigate(path: string, navigationParams?: INavigationParams, navigationOptions?: INavigationOptions) => Promise<void>` <br/> Triggers navigation to the specified `path` within the Impartner client application.              |
| `getState`               | `getState() => IRouterState` <br/> Returns current route state within the Impartner client application, including page title, path, and present query string parameters.                                                        |
| `getContentPageMetadata` | `getContentPageMetadata() => Promise<IContentPageMetadata[]>` <br/> Asynchronously retrieves a list of available page routes for navigation. **Only applicable within Impartner Portal host applications.**                     |
| `getCurrentPageMetadata` | `getCurrentPageMetadata() => Promise<IContentPageMetadata \| undefined>` <br/> Asynchronously returns the metadata for the currently loaded portal content page. **Only applicable within Impartner Portal host applications.** |

### IImpartnerLogger

| Service Type       | DI Token                 | Provided In                       |
| ------------------ | ------------------------ | --------------------------------- |
| `IImpartnerLogger` | `IMPARTNER_LOGGER_TOKEN` | `ImpartnerSdkModule.forRoot(...)` |

A service for simple logging behavior.

#### Methods

All below methods accept one `message` argument and an open-ended number of additional objects to be logged - the only difference between them is the message severity, which is denoted by the method name itself.

| Name    |                                                          |
| ------- | -------------------------------------------------------- |
| `trace` | `trace(message: string, ...argument: unknown[]) => void` |
| `info`  | `info(message: string, ...argument: unknown[]) => void`  |
| `log`   | `log(message: string, ...argument: unknown[]) => void`   |
| `debug` | `debug(message: string, ...argument: unknown[]) => void` |
| `warn`  | `warn(message: string, ...argument: unknown[]) => void`  |
| `error` | `error(message: string, ...argument: unknown[]) => void` |

### OrchestrationStudioService

| Service Type                 | DI Token                     | Provided In |
| ---------------------------- | ---------------------------- | ----------- |
| `OrchestrationStudioService` | `OrchestrationStudioService` | root        |

A service for interfacing with Impartner's Orchestration Studio product: getting available flow extension endpoints and making HTTP requests to those flow extension endpoints.

#### Methods

| Name                                 |                                                                                                                                                                                                                                                                                                                                                                                        |
| ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `getExtensionEndpoints`              | `getExtensionEndpoints() => Observable<Record<string, IExtensionEndpoint>>` <br/> Returns a dictionary of `IExtensionEndpoint`s by flow API name for the connected PRM environment / tenant.                                                                                                                                                                                           |
| `getExtensionEndpoint`               | `getExtensionEndpoint(flowApiName: string): Observable<IExtensionEndpoint \| null>` <br/> Returns a given flow API name's `IExtensionEndpoint` (or `null`).                                                                                                                                                                                                                            |
| `sendGetToExtensionEndpoint`         | `sendGetToExtensionEndpoint<T>(flowApiName: string, params?: IHttpClientOptions): Observable<IApiResult<T>>` <br/> Sends an HTTP `GET` request to the flow's extension endpoint by flow API name, optionally including additional `IHttpClientOptions`. Returns `IApiResult<T>`, where `T` is the flow's HTTP response body shape.                                                     |
| `sendPostToExtensionEndpoint`        | `sendPostToExtensionEndpoint<T, U>(flowApiName: string, body: U, params?: IHttpClientOptions): Observable<IApiResult<T>>` <br/> Sends an HTTP `POST` request to the flow's extension endpoint by flow API name, including a `POST` body (`U`) and optionally including additional `IHttpClientOptions`. Returns `IApiResult<T>`, where `T` is the flow's HTTP response body shape.     |
| `sendPutToExtensionEndpoint`         | `sendPutToExtensionEndpoint<T, U>(flowApiName: string, body: U, params?: IHttpClientOptions): Observable<IApiResult<T>>` <br/> Sends an HTTP `PUT` request to the flow's extension endpoint by flow API name, including a `PUT` body (`U`) and optionally including additional `IHttpClientOptions`. Returns `IApiResult<T>`, where `T` is the flow's HTTP response body shape.        |
| `getPrmEndpointForExtensionEndpoint` | `getPrmEndpointForExtensionEndpoint(extensionEndpoint: IExtensionEndpoint): string` <br/> Gets the relative PRM API endpoint URL used to send HTTP `GET` and `POST` requests for an extension endpoint.                                                                                                                                                                                |
| `sendAppEvent`                       | `sendAppEvent(eventType: string, payload: unknown): Observable<IAppEventResponse>` <br/> Dispatches an event of type `eventType` with value `payload` that will trigger any active flows using the `OnAppEvent` component configured to listen for the specified event type. Returns an `IAppEventResponse`, indicating which matching flows were triggered and/or failed to dispatch. |

## Local Development

All of the above documented services will also work in local development, provided the `environment` object passed to `ImpartnerSdkModule.forRoot(environment)` includes the property value `production: false`. However, there are some notable differences when running locally.

- `IImpartnerHttpClient`
  - HTTP calls made through `IImpartnerHttpClient` (including those by `ImpartnerMetadataService` and `ImpartnerObjectService`) will go to `localhost` with a root path matching the `impartnerEndpointUrl` property of the `environment` object. In order for these requests to adequately resolve, the Angular application's local development build must be configured to proxy calls on that path to an Impartner environment. For instructions on how to configure the proxy for local development, [consult the Angular documentation](https://angular.io/guide/build#proxying-to-a-backend-server).
- `IImpartnerRouter`
  - The `navigate` method will not trigger any actual navigation, but instead will log the provided arguments to the console and trigger a browser alert notifying that navigation was triggered.
  - The `getState` method will log a trace message to the console and return an object with the current query string parameters and the below `name` and `path` properties:
    ```typescript
    {
      name: 'Local Development',
      path: '/'
    }
    ```
  - The `getContentPageMetadata` method will log a trace message to the console and return a resolved Promise with an array of predefined, for-testing-only routes.