Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: otter sdk training - model extension #2411

Merged
merged 1 commit into from
Dec 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions apps/showcase/src/assets/trainings/sdk/program.json
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@
],
"mode": "interactive",
"commands": [
"npm install --legacy-peer-deps --ignore-scripts --force",
"npm install --legacy-peer-deps --ignore-scripts --no-audit --prefer-dedupe",
"npm run ng run sdk:build",
"npm run ng run tutorial-app:serve"
]
Expand Down Expand Up @@ -135,7 +135,7 @@
],
"mode": "interactive",
"commands": [
"npm install --legacy-peer-deps --ignore-scripts --force",
"npm install --legacy-peer-deps --ignore-scripts --no-audit --prefer-dedupe",
"npm run ng run app:serve"
]
}
Expand Down Expand Up @@ -182,7 +182,7 @@
"contentUrl": "@o3r-training/training-sdk/structure/src.json"
},
{
"path": "./libs/sdk/src/models",
"path": ".",
"contentUrl": "./steps/model-extension/exercise.json"
}
],
Expand All @@ -194,7 +194,7 @@
],
"mode": "interactive",
"commands": [
"npm install --legacy-peer-deps --ignore-scripts --force",
"npm install --legacy-peer-deps --ignore-scripts --no-audit --prefer-dedupe",
"npm run ng run tutorial-app:serve"
]
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Revived flight:
<pre>{{flight() | json }}</pre>
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { Component, inject, signal } from '@angular/core';
import { JsonPipe } from '@angular/common';
import { DummyApi, Flight } from 'sdk';

@Component({
selector: 'app-root',
standalone: true,
imports: [JsonPipe],
templateUrl: './app.component.html',
styleUrl: './app.component.scss'
})
export class AppComponent {
/** Title of the application */
public title = 'tutorial-app';

public readonly dummyApi = inject(DummyApi);

public readonly flight = signal<Flight | undefined>(undefined);

constructor() {
void this.loadDummyData();
}

async loadDummyData() {
const dummyData = await this.dummyApi.dummyGet({});
this.flight.set(dummyData);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { ApiFetchClient } from '@ama-sdk/client-fetch';
import { MockInterceptRequest, SequentialMockAdapter } from '@ama-sdk/core';
import { ApplicationConfig, provideZoneChangeDetection, importProvidersFrom } from '@angular/core';
import { provideRouter } from '@angular/router';
import { ConsoleLogger, Logger, LOGGER_CLIENT_TOKEN, LoggerService } from '@o3r/logger';
import { DummyApi } from 'sdk';
import { OPERATION_ADAPTER } from 'sdk/spec';
import { routes } from './app.routes';
import { additionalModules } from '../environments/environment';

function dummyApiFactory(logger: Logger) {
const apiConfig = new ApiFetchClient(
{
basePath: 'http://localhost:3000',
requestPlugins: [
new MockInterceptRequest({
adapter: new SequentialMockAdapter(
OPERATION_ADAPTER,
{
'/dummy_get': [{
mockData: {
originLocationCode: 'PAR',
destinationLocationCode: 'NYC'
}
}]
}
)
})
],
fetchPlugins: [],
logger
}
);
return new DummyApi(apiConfig);
}

export const appConfig: ApplicationConfig = {
providers: [
provideZoneChangeDetection({ eventCoalescing: true }),
provideRouter(routes),
importProvidersFrom(additionalModules),
{provide: LOGGER_CLIENT_TOKEN, useValue: new ConsoleLogger()},
{provide: DummyApi, useFactory: dummyApiFactory, deps: [LoggerService]}
]
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './base';
export * from './core';
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/* TODO Export your extended model and reviver instead of the original ones */
export type { Flight } from './flight';
export { reviveFlight } from './flight.reviver';
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/* TODO Modify the implementation of reviveFlightFactory to call `baseRevive` and add an extra id */
import type { reviveFlight } from '../../base/flight/flight.reviver';

/**
* Extended reviver for Flight
*
* @param baseRevive
*/
export function reviveFlightFactory<R extends typeof reviveFlight>(baseRevive: R) {
return baseRevive;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/* TODO create the type FlightCoreIfy which extends Flight, imported from the ../base folder */
/* Add an extra field `id: string` */

/**
* Extended type for Flight
*/
export type FlightCoreIfy = {

};
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './flight';
export * from './flight.reviver';
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// Export your core models here
export * from './flight';
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
### Objective
Let's continue with the use case of the previous exercise.\
In order to keep track of the user's current booking, it would be useful to generate an ID.\
To do this, we are going to create a new model which extends the previously generated `Flight` type.

### Exercise

#### Check out the base model
Before proceeding with the extension of the model, let's take a moment to review what is in the base model.
In the folder `libs/sdk/src/models/base/flight`, there are 3 files:
- `flight.ts` is the base model definition
- `flight.reviver.ts` is the reviver of the base model
- `index.ts` is the exposed entry point

By default, the revivers are only generated when needed:
- If `Date` fields are present and not stringified
- If `dictionaries` are present
- If `modelExtension` is enabled

If you open the file `libs/sdk/openapitools.json`, you can see that we have set the value of `allowModelExtension` to `true`.
This way, we make sure that the revivers will always be generated.

Now that we've seen the base model, let's start with the extension.

#### Creating the extended model
The extended model will follow a similar structure to the base model.
In the folder `libs/sdk/src/models/core/flight`, you will see the same 3 files mentioned before.

First, let's create the type `FlightCoreIfy` in `libs/sdk/src/models/core/flight.ts`.
This type should extend the type `Flight`, imported from the `base` folder and add a new field `id` of type `string`.

> [!WARNING]
> The naming convention requires the core model to contain the suffix `CoreIfy`.\
> You can find more information on core models in the
> <a href="https://github.com/AmadeusITGroup/otter/blob/main/docs/api-sdk/SDK_MODELS_HIERARCHY.md" target="_blank">SDK models hierarchy documentation</a>.

#### Creating the extended reviver
Now that you have your extended model, let's create the associated reviver in `libs/sdk/src/models/core/flight.reviver.ts`.\
This extended reviver will call the reviver of the base `Flight` model and add the `id` to the returned object.

#### Updating the exports
Once the core model and its reviver are created, we can go back to the base model to update the exported models and revivers.\
Update the file `libs/sdk/src/models/base/flight/index.ts` to export your extended model and reviver instead of the original.
sdo-1A marked this conversation as resolved.
Show resolved Hide resolved

#### Seeing the result
Your extension should now be working!\
Check out the preview to see if the `id` has been added to the model.

mrednic-1A marked this conversation as resolved.
Show resolved Hide resolved
#### Persistence of the change
You may have realized that we have modified a portion of code that was originally generated.
We don't want to lose the change that we made on `libs/sdk/src/models/base/flight/index.ts` next time it's regenerated.
To avoid that, we can add `src/models/base/flight/index.ts` to the `libs/sdk/.openapi-generator-ignore` file.
We cannot regenerate the SDK in the code editor due to a Java dependency but feel free to try it in a local project.

> [!TIP]
> Don't forget to check out the solution of this exercise!

Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Indicate the index.ts file you have override to redirect to custom interface definition
src/models/base/flight/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { FlightCoreIfy, reviveFlightFactory } from '../../core/flight';
import type { Flight as BaseModel } from './flight';
import { reviveFlight as baseReviver } from './flight.reviver';

export type Flight = FlightCoreIfy<BaseModel>;
export const reviveFlight = reviveFlightFactory(baseReviver);
export type { BaseModel as BaseFlight };
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import type { Flight } from '../../base/flight/flight';
import type { reviveFlight } from '../../base/flight/flight.reviver';
import type { FlightCoreIfy } from './flight';

/**
* Extended reviver for Flight
*
* @param baseRevive
*/
export function reviveFlightFactory<R extends typeof reviveFlight>(baseRevive: R) {
const reviver = <T extends Flight = Flight>(data: any, dictionaries?: any) => {
const revivedData = baseRevive<FlightCoreIfy<T>>(data, dictionaries);
if (!revivedData) { return; }
/* Set the value of your new fields here */
revivedData.id = 'sampleIdValue';
return revivedData;
};

return reviver;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import type { Flight } from '../../base/flight/flight';
import type { IgnoreEnum } from '@ama-sdk/core';

/**
* Extended type for Flight
*/
export type FlightCoreIfy<T extends IgnoreEnum<Flight>> = T & {
id: string;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './flight';
export * from './flight.reviver';
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// Export your core models here
export * from './flight';
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './base';
export * from './core';
8 changes: 4 additions & 4 deletions packages/@ama-sdk/core/src/plugins/mock-intercept/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Mock intercept plugin

The mock interception statregy works based on two interceptions: request and fetch. For each interception, a plugin has been made.
The mock interception strategy works based on two interceptions: request and fetch. For each interception, a plugin has been made.

## Mock intercept request plugin

Expand Down Expand Up @@ -66,7 +66,7 @@ Example of usage:
*/
import {OPERATION_ADAPTER} from '@ama-sdk/sdk/spec/operation-adapter';

const myRandomAdapter: new RandomMockAdapter(
const myRandomAdapter = new RandomMockAdapter(
OPERATION_ADAPTER,
{
// Mock data for createCart operation
Expand All @@ -76,7 +76,7 @@ const myRandomAdapter: new RandomMockAdapter(
}
);

const myRandomAdapter: new SequentialMockAdapter(
const myRandomAdapter = new SequentialMockAdapter(
OPERATION_ADAPTER,
{
// Mock data for createCart operation
Expand Down Expand Up @@ -110,7 +110,7 @@ Example of usage:
*/
import {OPERATION_ADAPTER} from '@ama-sdk/sdk/spec/operation-adapter';

const myAdapter: new RandomMockAdapter(
const myAdapter = new RandomMockAdapter(
OPERATION_ADAPTER,
() => {
return fetch('http://my-test-server/getMocks');
Expand Down
4 changes: 4 additions & 0 deletions packages/@o3r-training/training-sdk/open-api.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ paths:
responses:
200:
description: "Successful operation"
content:
application/json:
schema:
$ref: '#/components/schemas/Flight'
components:
schemas:
Flight:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Flight } from '../../models/base/flight/index';

import { DummyApi, DummyApiDummyGetRequestData } from './dummy-api';

Expand All @@ -6,9 +7,9 @@ export class DummyApiFixture implements Partial<Readonly<DummyApi>> {
/** @inheritDoc */
public readonly apiName = 'DummyApi';

/**
/**
* Fixture associated to function dummyGet
*/
public dummyGet: jest.Mock<Promise<void>, [DummyApiDummyGetRequestData]> = jest.fn();
public dummyGet: jest.Mock<Promise<Flight>, [DummyApiDummyGetRequestData]> = jest.fn();
}

13 changes: 7 additions & 6 deletions packages/@o3r-training/training-sdk/src/api/dummy/dummy-api.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Api, ApiClient, ApiTypes, computePiiParameterTokens, RequestBody, RequestMetadata, } from '@ama-sdk/core';
import { Flight, reviveFlight } from '../../models/base/flight/index';
import { Api, ApiClient, ApiTypes, computePiiParameterTokens, RequestBody, RequestMetadata } from '@ama-sdk/core';

/** Parameters object to DummyApi's dummyGet function */
export interface DummyApiDummyGetRequestData {
Expand Down Expand Up @@ -27,20 +28,20 @@ export class DummyApi implements Api {
}

/**
*
*
*
*
* @param data Data to provide to the API call
* @param metadata Metadata to pass to the API call
*/
public async dummyGet(data: DummyApiDummyGetRequestData, metadata?: RequestMetadata<string, string>): Promise<void> {
public async dummyGet(data: DummyApiDummyGetRequestData, metadata?: RequestMetadata<string, 'application/json'>): Promise<Flight> {
const queryParams = this.client.extractQueryParams<DummyApiDummyGetRequestData>(data, [] as never[]);
const metadataHeaderAccept = metadata?.headerAccept || 'application/json';
const headers: { [key: string]: string | undefined } = {
'Content-Type': metadata?.headerContentType || 'application/json',
...(metadataHeaderAccept ? {'Accept': metadataHeaderAccept} : {})
};

let body: RequestBody = '';
const body: RequestBody = '';
const basePath = `${this.client.options.basePath}/dummy`;
const tokenizedUrl = `${this.client.options.basePath}/dummy`;
const tokenizedOptions = this.client.tokenizeRequestOptions(tokenizedUrl, queryParams, this.piiParamTokens, data);
Expand All @@ -59,7 +60,7 @@ export class DummyApi implements Api {
const options = await this.client.getRequestOptions(requestOptions);
const url = this.client.prepareUrl(options.basePath, options.queryParams);

const ret = this.client.processCall<void>(url, options, ApiTypes.DEFAULT, DummyApi.apiName, { 200: undefined } , 'dummyGet');
const ret = this.client.processCall<Flight>(url, options, ApiTypes.DEFAULT, DummyApi.apiName, { 200: reviveFlight } , 'dummyGet');
return ret;
}

Expand Down
Loading