@totvslabs/carol-app-fe-sdk
v0.1.24
Published
[![Build status](https://badge.buildkite.com/e3758c83d75b85802da1050c70a0aa6d1efc9d00d9a8eab173.svg)](https://buildkite.com/totvslabs/carol-fe-sdk)
Downloads
15
Keywords
Readme
CarolApp FrontEnd SDK
SDK to support the development of Carol Apps with Angular.
Starting the development of a new Carol App? Check out our official seed project, that already includes the Carol FE SDK and PO UI preconfigured.
Installation
On your current Angular project:
npm install @totvslabs/carol-app-fe-sdk
Setup your Angular app
1. Setup your Angular server for development
1.1 Allow your app to import json files
On your project, change the tsconfig.json
compiler Options to allow import json values in the project.
{
...
"compilerOptions": {
...
"resolveJsonModule": true,
"allowSyntheticDefaultImports": true
...
}
1.2 Create a proxy file
For development purposes, a proxy needs to be configured to divert certain URLs to Carol's backend. It is a good practice to call this file proxy.conf.json
and to keep it inside your project's root or src folder.
We want to proxy http calls for paths starting as /api
and /sql
, and for that your proxy file should look like that, replacing the values CAROL_ORGANIZATION_NAME
and CAROL_ENVIRONMENT_NAME
:
{
"carolOrganization": "CAROL_ORGANIZATION_NAME",
"carolEnvironment": "CAROL_ENVIRONMENT_NAME",
"/api/*": {
"target": "https://CAROL_ORGANIZATION_NAME.carol.ai",
"secure": true,
"logLevel": "debug",
"changeOrigin": true
},
"/sql/*": {
"target": "https://api.carol.ai/sql/v1/query",
"secure": true,
"logLevel": "debug",
"changeOrigin": true,
"pathRewrite": {
"^/sql": "/"
}
}
}
1.3 Introduce your proxy to Angular serve
After properly setting up your proxy configuration file, you need to point your angular.json
file, with the following entries.
...
"architect": {
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "your-application-name:build",
"proxyConfig": "proxy.conf.json"
},
...
2. App initialization
The SDK needs certain parameters to be defined during the app initialization in order to work properly.
In dev mode they are:
- Organization;
- Environment;
- Domain;
In prod mode they are automatically detected from the URL.
The recommended way to do this is through a factory function and then providing it to the APP_INITIALIZER token. Angular will then execute it during the app initialization.
Your app.module.ts
should look like this:
import { NgModule, isDevMode, APP_INITIALIZER } from '@angular/core';
import { RouterModule } from '@angular/router';
import { HttpClientModule } from '@angular/common/http';
import { BrowserModule } from '@angular/platform-browser';
import { CarolAuthService, CarolSdkModule } from '@totvslabs/carol-app-fe-sdk';
import conf from 'proxy.conf.json';
function appInitializer(carolAuth: CarolAuthService) {
return () =>
isDevMode()
? carolAuth
.setDomain(conf['/api/*'].target)
.setOrganization(conf.carolOrganization)
.setEnvironment(conf.carolEnvironment)
.appStart()
: carolAuth.appStart();
}
@NgModule({
declarations: [],
imports: [
CarolSdkModule,
HttpClientModule,
RouterModule.forRoot([]),
],
providers: [
{
provide: APP_INITIALIZER,
useFactory: appInitializer,
deps: [CarolAuthService],
multi: true
},
]
})
Important
- Notice how in both modes (dev and prod) the appStart function must be called.
- The CarolSdkModule must always be imported.
- As the SDK relies on route navigations and HTTP requests, both
HttpClientModule
andRouterModule
must be imported by the parent application
Ready to go!
Now, when your Angular app starts, it will be already authenticated and ready to communicate with Carol.
Check the available SDK Apis bellow and good coding.
Deploying to Carol
1. Changes required for the app to be hosted on the Carol Platform
1.1 index.html base tag href
property
The href
attribute specifies to the browser the base URL for all relative URLs on a page. Carol apps are required to specify this property with the .
value.
<base href=".">
1.2 Angular route strategy
Web apps hosted in the Carol platform are also required to use the HashLocationStrategy.
In your app's main module, you have to declare your routes with an aditional options object describing it:
RouterModule.forRoot(routes, {useHash: true})
2. Bundling and publishing to Carol
The SDK provides scripts to automate the bundling process -- preparing your application accordingly to the structure Carol expects, and to publish it to the platform.
The entire publishing process can be achieved by replacing the build script on your package.json
file with the following:
build: "ng build && npx prepare-bundle --package=@totvslabs/carol-app-fe-sdk && npx upload-bundle --package=@totvslabs/carol-app-fe-sdk"
And then running "npm run build".
2.1 Parameters
The scripts accept several parameters that can be used for automation / QOL purposes:
2.1.1 Prepare bundle
path
: Relative path to the compiled application's root folder;
2.1.1 Upload bundle
path
: Relative path to the prepared .zip bundle;
organization
: The Carol organization name of where your application will be hosted;
environment
: The Carol environment name of where your application will be hosted;
app-name
: Name of the application where your application will be hosted;
username
: Username used to authenticate on the Carol platform;
password
: Password used to authenticate on the Carol platform;
access-token
: Access Token used to authenticate on the platform (alternative to username and password);
connector-id
: Connector ID used to authenticate on the platform is using an API token;
2.2 Manual instructions
Manual instructions to prepare and publish your Carol Application
2.2.1 Preparing your compiled application's file structure
Carol expects your project bundle to follow the structure below:
.zip file (the compressed file name doesn't matter)
├── 'site' folder (the folder name MUST be 'site')
│ ├── Your project's files.
│ ├── ...
│ ├── ...
│ ├── ...
Our SDK provides you with a script that automatically organizes this structure for you.
You can execute it by calling npx prepare-bundle --package=@totvslabs/carol-app-fe-sdk
, or prepare-bundle
if you have the SDK installed globally.
The command must be executed in your project's root folder or passing a path
parameter with the relative path to your compiled project.
2.2.2 Publishing your app to Carol
With your zip file prepared, you can either upload it to carol manually through the platform UI, or use a second script provided by the SDK.
The script can be executed by calling npx upload-bundle --package=@totvslabs/carol-app-fe-sdk
or upload-bundle
if you have the SDK installed globally.
The command must be executed in your project's root folder or passing a path
parameter with the relative path to your zip file.
APIs:
Query data from Carol
CarolSqlQueryService
runSQL(sql: string, pageSize?: number, page?: number): Observable<SqlQueryResponseDTO>
Runs a SQL query and emits the result once it completes.
getPage(queryId: string, page: number): Observable<SqlQueryResponseDTO>
Gets the specified page of a previously run SQL query. Requires the queryId which is returned with the result set after running the runSQL method.
runSyncSql(sql: string, pageSize?: number, page?: number): Observable<SqlQueryResponseDTO>
Runs a SQL query in a synchronous manner, without pooling. Normally should be avoided as its susceptible to timeouts in bigger queries.
tablePreview(tableName: string, maxRows?: number): Observable<SqlPreviewResponseDTO>
Returns a cached preview of the specified table.
Datamodels
CarolDatamodelsService
getDatamodels(): Promise<Datamodels>
Returns a compilation of all the datamodels in the current environment, its fields and types.
Authentication
CarolAuthService
appStart(): void;
Method to be called when the app is ready to validate and handle the login flow. If in dev mode, organization, environment and domain must be set using the methods described below.
setSelfLogin(selfLogin: boolean): this;
Flag that defines if the app will be using the Carol OAuth login application or if the carol-app will be handling the login flow. Defaults to false.
setOrganization(organization: string): this;
Defines the organization that will be used by the internal routines of the SDK in dev mode. In production this method can be disregarded as the info will be get from the browser URL.
setEnvironment(environment: string): this;
Defines the environment that will be used by the internal routines of the SDK in dev mode. In production this method can be disregarded as the info will be get from the browser URL.
setDomain(domain: string): this;
Defines the domain that will be used by the internal routines of the SDK in dev mode. In production this method can be disregarded as the info will be get from the browser URL.
async setSessionToken(sessionToken: string): void;
Defines the current session token. Will handle all the logic related to session tokens such as validating, setting to local storage and adding to an HttpInterceptor. To be used together with selfLogin.
get organization(): string;
Returns the current organization;
get environment(): string;
Returns the current environment;
get domain(): string;
Returns the current domain;
get sessionToken(): string;
Returns the current session token;
get selfLogin(): boolean;
Returns the current value of the selfLogin flag;
login(userName: string, password: string): Promise<Subscription>;
Manually creates a Carol Session. To be used together with selfLogin;
logout(): Promise<void>;
Ends the current Carol Session and redirects the user to login. In selfLogin mode the carol-app is responsible for the redirect.
loggedIn$: Observable<boolean>
Observable to receive changes about the carol session status.