Typescript-fetch Example
Using the Generator
Inside our project we created a specs
directory to place the household.yaml
.
For the generator we will use the typescript-fetch
as provided from the openAPI Generator documentation, and for
convenience we named the outupt_folder
as typescript-fetch
.
With the command from the run the code generator section, using the household.yaml file, we generate our client.
- npm
- yarn
npx openapi-generator-cli generate -i specs/household.yaml -g typescript-fetch -o typescript-fetch/
yarn openapi-generator-cli generate -i specs/household.yaml -g typescript-fetch -o typescript-fetch/
For convenience and demonstration reasons we use the already existing Envizage's GuestService, HttpClient, ScenarioService, withInterceptor services and IHttpClient, IScenario models. These can be installed via npm or yarn in our project using the following commands:
- npm
- yarn
npm install @envizage/servises @envizage/model
yarn add @envizage/servises @envizage/model
We do that in order to be able to login as a guest user and create a scenario, so that we can then manipulate the household using the generated client.
Generated outcome
The openAPI Generator will then produce an api client in a structure that looks similiar (if not identical) to this:
├─ typescript-fetch
│ ├─ .openapi-generator
│ │ ├─ FILES
│ │ └─ VERSION
│ ├─ apis
│ │ ├─ ChildrenApi.ts
│ │ ├─ ParentsApi.ts
│ │ ├─ PartnerApi.ts
│ │ ├─ PersonsApi.ts
│ │ ├─ PrimaryApi.ts
│ │ └─ index.ts
│ └─ models
│ ├─ ChildDto.ts
│ ├─ PageableObject.ts
│ ├─ PageChildDto.ts
│ ├─ PageParentDto.ts
│ ├─ PagePersonDto.ts
│ ├─ ParentDto.ts
│ ├─ PartnerDto.ts
│ ├─ PersonDto.ts
│ ├─ PrimaryDto.ts
│ ├─ SortObject.ts
│ └─ index.ts
├─ .openapi-genarator-ignore
├─ index.ts
└─ runtime.ts
FILES
is a text file that lists all the generated files.VERSION
is a file that lists the openAPI Tools version used..openapi-generator-ingore
is a file that documents the files that you will not want to overwrite in the future.runtime.ts
is a file where various runtime parameters are described.
In this example we will make use of the apis
and model
files, as well as the runtime.ts
file, inside our own node application or typescript script.
Using the Client
At the top of the runtime.ts
file we need to specify the base url:
export const BASE_PATH = "https://api.envizage.me".replace(//+$/, "");
In each api file we can find what their relative requests to the Envizage's APIs require as arguments.
For example in the primaryApi.ts
to get the primary person:
/**
* Retrieve the Primary Person
* Retrieve
*/
async getPrimaryRaw(requestParameters: GetPrimaryRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<PrimaryDto>> {
if (requestParameters.scenarioId === null || requestParameters.scenarioId === undefined) {
throw new runtime.RequiredError('scenarioId','Required parameter requestParameters.scenarioId was null or undefined when calling getPrimary.');
}
const queryParameters: any = {};
const headerParameters: runtime.HTTPHeaders = {};
const response = await this.request({
path: `/scenarios/{scenarioId}/persons/primary`.replace(`{${"scenarioId"}}`, encodeURIComponent(String(requestParameters.scenarioId))),
method: 'GET',
headers: headerParameters,
query: queryParameters,
}, initOverrides);
return new runtime.JSONApiResponse(response, (jsonValue) => PrimaryDtoFromJSON(jsonValue));
}
And to update the primary person:
/**
* Updates the existing primary person created with the household. This person already exists.
* Update
*/
async updatePrimaryRaw(requestParameters: UpdatePrimaryRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<PrimaryDto>> {
if (requestParameters.scenarioId === null || requestParameters.scenarioId === undefined) {
throw new runtime.RequiredError('scenarioId','Required parameter requestParameters.scenarioId was null or undefined when calling updatePrimary.');
}
if (requestParameters.primaryDto === null || requestParameters.primaryDto === undefined) {
throw new runtime.RequiredError('primaryDto','Required parameter requestParameters.primaryDto was null or undefined when calling updatePrimary.');
}
const queryParameters: any = {};
const headerParameters: runtime.HTTPHeaders = {};
headerParameters['Content-Type'] = 'application/json';
const response = await this.request({
path: `/scenarios/{scenarioId}/persons/primary`.replace(`{${"scenarioId"}}`, encodeURIComponent(String(requestParameters.scenarioId))),
method: 'PUT',
headers: headerParameters,
query: queryParameters,
body: PrimaryDtoToJSON(requestParameters.primaryDto),
}, initOverrides);
return new runtime.JSONApiResponse(response, (jsonValue) => PrimaryDtoFromJSON(jsonValue));
}
In general the get requests require as arguments:
- The requestParameters with the
scenarioId
of the scenario that we will create:
export interface GetPrimaryRequest {
scenarioId: string;
};
- A header for the request with the
authToken
created when we logged in as guests:
{ headers: [ [ 'Authorization', `Bearer ${authToken}` ] ] }
The put and post requests require as arguments:
- The requestParameters with the
scenarioId
of the scenario that we will create and the person's entity we want to create or update:
export interface UpdatePrimaryRequest {
scenarioId: string;
primaryDto: PrimaryDto;
}
- A header for the request with the
authToken
created when we logged in as guests and the content type of the request:
{ headers: [ [ 'Authorization', `Bearer ${authToken}` ], [ 'Content-Type', 'application/json' ] ] }
The delete requests require as arguments:
- The requestParameters with the
scenarioId
of the scenario that we will create:
export interface DeletePartnerRequest {
scenarioId: string;
}
- A header for the request with the
authToken
created when we logged in as guests:
{ headers: [ [ 'Authorization', `Bearer ${authToken}` ] ] }
In order to see these in action we create a typescript file, for example: index.ts
.
Imports
First we need to handle all of our imports:
import {
GuestService,
HttpClient,
ScenarioService,
withInterceptor
} from "@envizage/services";
import * as runtime from './typescript-fetch/runtime';
import {
IHttpClient,
IScenario
} from "@envizage/model";
import {
ChildDto,
ChildrenApi,
CreateChildRequest,
CreateParentRequest,
CreatePartnerRequest,
DeletePartnerRequest,
DeletePersonRequest,
GetChildrenRequest,
GetParentsRequest,
GetPartnerRequest,
GetPersonRequest,
GetPersonsRequest,
GetPrimaryRequest,
ParentDto,
ParentsApi,
PartnerApi,
PartnerDto,
PersonDto,
PersonsApi,
PrimaryApi,
PrimaryDto,
UpdatePartnerRequest,
UpdatePersonRequest,
UpdatePrimaryRequest,
} from "./typescript-fetch";
Services instantiation
Then we instantiate the services we are going to need and login as a guest user to create a scenario:
// Service instantiations
const JsonClient = withInterceptor((url, params, headerMap, body) => {
const clonedHeaders = headerMap ? (JSON.parse(JSON.stringify(headerMap)) as [string, string][]) : [];
clonedHeaders.push(["Accept", "application/json"]);
clonedHeaders.push(["Content-type", "application/json"]);
return {
url,
params,
headerMap: clonedHeaders,
body,
};
})(HttpClient);
let API_URL = runtime.BASE_PATH;
let AuthenticatedJsonClient: IHttpClient;
const guestService = new GuestService(JsonClient, API_URL);
let scenarioService: ScenarioService;
let primaryService: PrimaryApi;
let partnerService: PartnerApi;
let childrenService: ChildrenApi;
let parentsService: ParentsApi;
let personsService: PersonsApi;
let scenario: IScenario;
let authToken: string;
let clonedHeaders:[string, string][];
async function householdAPIs() {
console.log('API_URL:', API_URL);
// Login as guest.
await guestService.login().then((res) => {
AuthenticatedJsonClient = withInterceptor((url, params, headerMap, body) => {
clonedHeaders = headerMap ? (JSON.parse(JSON.stringify(headerMap)) as [string, string][]) : [];
clonedHeaders.push(['Authorization', `Bearer ${res?.token?.accessToken}`]);
authToken = res.token.accessToken;
return {
url, params, headerMap: clonedHeaders, body
}
})(JsonClient);
scenarioService = new ScenarioService(AuthenticatedJsonClient, API_URL);
primaryService = new PrimaryApi;
partnerService = new PartnerApi;
childrenService = new ChildrenApi;
parentsService = new ParentsApi;
personsService = new PersonsApi;
});
// Create a scenario to instantiate a primary person
scenario = await scenarioService.create({ current: false, name: 'Test_Scenario' });
}
From here on, is were we will make use of the client API's and models that the generator produced.
Primary API
Get and update the primary household person.
Get primary person:
// Primary API requests
let getPrimaryRequest: GetPrimaryRequest = {
scenarioId: scenario.id || ''
};
let primary = await primaryService.getPrimary(getPrimaryRequest, {headers: clonedHeaders});
console.log('Primary:', primary);
Response:
{
description: undefined,
educationLevel: 'SECONDARY_EDUCATION',
expectedRetirementAge: 67,
gender: 'FEMALE',
healthStatus: 'EXCELLENT',
id: '647f2b67d194370ba9d6b758',
jobType: 'ACTIVE',
lastName: undefined,
maritalStatus: 'UNSPECIFIED',
name: 'Me',
primary: true,
properties: {},
yearOfBirth: 1981
}
Update primary person:
let primaryPerson: PrimaryDto = {...primary};
primaryPerson.yearOfBirth = 1985;
let primaryUpdateRequest: UpdatePrimaryRequest = {
scenarioId: scenario.id || '',
primaryDto: primaryPerson
}
let primaryUpdate = await primaryService.updatePrimary(primaryUpdateRequest, {headers: [['Authorization', `Bearer ${authToken}`], ['Content-Type', 'application/json']]});
console.log('Updated Primary:', primaryUpdate);
Response:
{
description: undefined,
educationLevel: 'SECONDARY_EDUCATION',
expectedRetirementAge: 67,
gender: 'FEMALE',
healthStatus: 'EXCELLENT',
id: '647f2b67d194370ba9d6b758',
jobType: 'ACTIVE',
lastName: undefined,
maritalStatus: 'UNSPECIFIED',
name: 'Me',
primary: true,
properties: {},
yearOfBirth: 1985
}
Partner API
Create, get, update and delete a partner.
Create a partner:
// Partner API
let partnerPerson: PartnerDto = {...primary};
partnerPerson.gender = "MALE"
let createPartnerRequest: CreatePartnerRequest = {
scenarioId: scenario.id || '',
partnerDto: partnerPerson
}
let partner = await partnerService.createPartner(createPartnerRequest, {headers: [['Authorization', `Bearer ${authToken}`], ['Content-Type', 'application/json']]});
console.log('Partner:', partner);
Response:
{
description: undefined,
educationLevel: 'SECONDARY_EDUCATION',
expectedRetirementAge: 67,
gender: 'MALE',
healthStatus: 'EXCELLENT',
id: '647f2b687fa82c3678dca118',
jobType: 'ACTIVE',
lastName: undefined,
maritalStatus: 'UNSPECIFIED',
name: 'Me',
primary: true,
properties: {},
yearOfBirth: 1981
}
Get a partner:
let getPartnerRequest: GetPartnerRequest = {
scenarioId: scenario.id || ''
}
let partnerGet = await partnerService.getPartner(getPartnerRequest, {headers: clonedHeaders});
console.log('Get Partner:', partnerGet);
Response:
{
description: undefined,
educationLevel: 'SECONDARY_EDUCATION',
expectedRetirementAge: 67,
gender: 'MALE',
healthStatus: 'EXCELLENT',
id: '647f2b687fa82c3678dca118',
jobType: 'ACTIVE',
lastName: undefined,
maritalStatus: 'UNSPECIFIED',
name: 'Me',
primary: true,
properties: {},
yearOfBirth: 1981
}
Update a partner:
let updatePartnerRequest: UpdatePartnerRequest = {
scenarioId: scenario.id || '',
partnerDto: partnerGet
}
partnerGet.yearOfBirth = 1985;
let partnerUpdate = await partnerService.updatePartner(updatePartnerRequest, {headers: [['Authorization', `Bearer ${authToken}`], ['Content-Type', 'application/json']]});
console.log('Updated Partner:', partnerUpdate);
Response:
{
description: undefined,
educationLevel: 'SECONDARY_EDUCATION',
expectedRetirementAge: 67,
gender: 'MALE',
healthStatus: 'EXCELLENT',
id: '647f2b687fa82c3678dca118',
jobType: 'ACTIVE',
lastName: undefined,
maritalStatus: 'UNSPECIFIED',
name: 'Me',
primary: true,
properties: {},
yearOfBirth: 1985
}
let deletePartnerRequest: DeletePartnerRequest = {
scenarioId: scenario.id || ''
};
let partnerDelete = await partnerService.deletePartner(deletePartnerRequest, {headers: clonedHeaders});
Children API
Create and get a child.
Create a child:
// Children API
let childPerson: ChildDto = {
gender: "UNSPECIFIED",
healthStatus: "CRITICALLY_ILL",
maritalStatus: "UNSPECIFIED",
yearOfBirth: 2020
}
let createChildRequest: CreateChildRequest = {
scenarioId: scenario.id || '',
childDto: childPerson
}
let childCreate = await childrenService.createChild(createChildRequest, {headers: [['Authorization', `Bearer ${authToken}`], ['Content-Type', 'application/json']]});
console.log('Created child:', childCreate);
Response:
{
description: undefined,
gender: 'UNSPECIFIED',
healthStatus: 'CRITICALLY_ILL',
id: '647f2b68d194370ba9d6b7b0',
lastName: undefined,
maritalStatus: 'UNSPECIFIED',
name: undefined,
primary: false,
properties: {},
yearOfBirth: 2020
}
Get children:
let getChildrenRequest: GetChildrenRequest = {
scenarioId: scenario.id || ''
};
let childrenGet = await childrenService.getChildren(getChildrenRequest, {headers: clonedHeaders});
console.log('Get children:', childrenGet.content);
Response:
[
{
description: undefined,
gender: 'UNSPECIFIED',
healthStatus: 'CRITICALLY_ILL',
id: '647f2b68d194370ba9d6b7b0',
lastName: undefined,
maritalStatus: 'UNSPECIFIED',
name: undefined,
primary: false,
properties: {},
yearOfBirth: 2020
}
]
Note that the response here is an array, because you can create multiple children.
Parent API
Create and get a parent.
Create a parent:
// Parent API
let parentPerson: ParentDto = {
educationLevel: "NO_EDUCATION",
expectedRetirementAge: 0,
gender: "FEMALE",
healthStatus: "CRITICALLY_ILL",
jobType: "UNEMPLOYED",
maritalStatus: "UNSPECIFIED",
yearOfBirth: 1965
};
let createParentRequest: CreateParentRequest = {
scenarioId: scenario.id || '',
parentDto: parentPerson
};
let parentCreate = await parentsService.createParent(createParentRequest, {headers: [['Authorization', `Bearer ${authToken}`], ['Content-Type', 'application/json']]});
console.log('Created parent:', parentCreate);
Response:
{
description: undefined,
educationLevel: 'NO_EDUCATION',
expectedRetirementAge: 0,
gender: 'FEMALE',
healthStatus: 'CRITICALLY_ILL',
id: '647f2b69d194370ba9d6b7d6',
jobType: 'UNEMPLOYED',
lastName: undefined,
maritalStatus: 'UNSPECIFIED',
name: undefined,
primary: false,
properties: {},
yearOfBirth: 1965
}
Get parents:
let getParentRequest: GetParentsRequest = {
scenarioId: scenario.id || ''
};
let parentGet = await parentsService.getParents(getParentRequest, {headers: clonedHeaders});
console.log('Get parent:', parentGet.content);
Response:
[
{
description: undefined,
educationLevel: 'NO_EDUCATION',
expectedRetirementAge: 0,
gender: 'FEMALE',
healthStatus: 'CRITICALLY_ILL',
id: '647f2b69d194370ba9d6b7d6',
jobType: 'UNEMPLOYED',
lastName: undefined,
maritalStatus: 'UNSPECIFIED',
name: undefined,
primary: false,
properties: {},
yearOfBirth: 1965
}
]
Note that the response here is an array, because you can create two parents.
Persons API
Get a person or persons, update and delete a child or parent.
Get a person:
// Persons API
let getPersonRequest: GetPersonRequest = {
scenarioId: scenario.id || '',
personId: primary.id || ''
};
let personGet = await personsService.getPerson(getPersonRequest, {headers: clonedHeaders});
console.log('Get Person:', personGet);
Response:
{
description: undefined,
gender: 'FEMALE',
healthStatus: 'EXCELLENT',
id: '648033f1e4fe1411925fc7cf',
lastName: undefined,
maritalStatus: 'UNSPECIFIED',
name: 'Me',
primary: true,
properties: {},
yearOfBirth: 1985
}
Get all persons:
let getPersonsRequest: GetPersonsRequest = {
scenarioId: scenario.id || ''
};
let personsGet = await personsService.getPersons(getPersonsRequest, {headers: clonedHeaders});
console.log('Get Persons:', personsGet.content);
Response:
[
{
description: undefined,
gender: 'FEMALE',
healthStatus: 'EXCELLENT',
id: '648033f1e4fe1411925fc7cf',
lastName: undefined,
maritalStatus: 'UNSPECIFIED',
name: 'Me',
primary: true,
properties: {},
yearOfBirth: 1985
},
{
description: undefined,
gender: 'UNSPECIFIED',
healthStatus: 'CRITICALLY_ILL',
id: '648033f2c6f3cb4b641bf66c',
lastName: undefined,
maritalStatus: 'UNSPECIFIED',
name: undefined,
primary: false,
properties: {},
yearOfBirth: 2020
},
{
description: undefined,
gender: 'FEMALE',
healthStatus: 'CRITICALLY_ILL',
id: '648033f2c6f3cb4b641bf692',
lastName: undefined,
maritalStatus: 'UNSPECIFIED',
name: undefined,
primary: false,
properties: {},
yearOfBirth: 1965
}
]
Update a person:
let updatedPerson: PersonDto = personGet;
updatedPerson.maritalStatus = "MARRIED";
let updatePersonRequest: UpdatePersonRequest = {
scenarioId: scenario.id || '',
personId: updatedPerson.id || '',
personDto: updatedPerson
};
let personUpdate = await personsService.updatePerson(updatePersonRequest, {headers: [['Authorization', `Bearer ${authToken}`], ['Content-Type', 'application/json']]});
console.log('Updated person:', personUpdate);
Response:
{
description: undefined,
gender: 'FEMALE',
healthStatus: 'EXCELLENT',
id: '648033f1e4fe1411925fc7cf',
lastName: undefined,
maritalStatus: 'MARRIED',
name: 'Me',
primary: true,
properties: {},
yearOfBirth: 1985
}
Delete a person:
let personToDelete: PersonDto | undefined = parentGet.content?.find(p => p.healthStatus === "CRITICALLY_ILL");
let deletePersonRequest: DeletePersonRequest = {
scenarioId: scenario.id || '',
personId: personToDelete?.id || ''
};
let personDelete = await personsService.deletePerson(deletePersonRequest, {headers: clonedHeaders});