Skip to content

Commit

Permalink
feat: otter sdk training - model extension
Browse files Browse the repository at this point in the history
  • Loading branch information
sdo-1A authored and fpaul-1A committed Nov 19, 2024
1 parent 96522c5 commit 558242b
Show file tree
Hide file tree
Showing 30 changed files with 684 additions and 404 deletions.
2 changes: 2 additions & 0 deletions apps/showcase/project.json
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@
"defaultConfiguration": "production",
"dependsOn": [
"^build",
"^extract-folder-structure",
"generate-translations",
"generate-theme",
"generate-dark-theme",
Expand All @@ -176,6 +177,7 @@
"dependsOn": [
"^build-builders",
"^build",
"^extract-folder-structure",
"copy-training-assets",
"prepare-training"
]
Expand Down
68 changes: 68 additions & 0 deletions apps/showcase/schemas/webcontainer-file-system-tree.schema.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
{
"$schema": "http://json-schema.org/draft-07/schema",
"$id": "WebContainerFileSystemTreeSchema",
"description": "Schema of a webcontainer api file system tree",
"required": ["fileSystemTree"],
"properties": {
"fileSystemTree": {
"$ref": "#/definitions/FileSystemTree"
}
},
"definitions": {
"FileSystemTree": {
"type": "object",
"additionalProperties": {
"oneOf": [
{"$ref": "#/definitions/DirectoryNode"},
{"$ref": "#/definitions/FileNode"},
{"$ref": "#/definitions/SymlinkNode"}
]
}
},
"DirectoryNode": {
"type": "object",
"required": ["directory"],
"properties": {
"directory": {
"$ref": "#/definitions/FileSystemTree"
}
}
},
"FileNode": {
"type": "object",
"required": [
"file"
],
"properties": {
"file": {
"type": "object",
"description": "Metadata type",
"required": ["contents"],
"properties": {
"contents": {
"type": "string"
}
}
}
}
},
"SymlinkNode": {
"type": "object",
"required": [
"file"
],
"properties": {
"file": {
"type": "object",
"description": "Metadata type",
"required": ["symlink"],
"properties": {
"symlink": {
"type": "string"
}
}
}
}
}
}
}
4 changes: 3 additions & 1 deletion apps/showcase/scripts/prepare-training-exercises/index.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ void (async () => {
const exerciseStructure = await getFilesTree([{isDir: true, path: `${filePath}`}], {readdir, readFile});
const [_, commonPath, folderName] = folder.match('(.*)/(exercise|solution)');
const targetPath = join(commonPath, `${folderName}.json`);
const content = JSON.stringify(exerciseStructure);
const content = JSON.stringify({
fileSystemTree: exerciseStructure
});
await writeFile(targetPath, content);
}
})();
10 changes: 7 additions & 3 deletions apps/showcase/src/assets/trainings/sdk/program.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,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 @@ -95,7 +95,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 All @@ -111,6 +111,10 @@
"path": ".",
"contentUrl": "./shared/monorepo-template.json"
},
{
"path": ".",
"contentUrl": "./shared/training-sdk-app.json"
},
{
"path": "./libs/sdk/src",
"contentUrl": "@o3r-training/training-sdk/structure/src.json"
Expand All @@ -128,7 +132,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
748 changes: 371 additions & 377 deletions apps/showcase/src/assets/trainings/sdk/shared/monorepo-template.json

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"$schema": "../../../../../schemas/webcontainer-file-system-tree.schema.json",
"fileSystemTree": {
"apps": {
"directory": {
"tutorial-app": {
"directory": {
"src": {
"directory": {
"app": {
"directory": {
"app.component.html": {
"file": {
"contents": "Revived flight:\r\n<pre>{{flight() | json }}</pre>"
}
},
"app.component.ts": {
"file": {
"contents": "import { Component, inject, signal } from '@angular/core';\nimport { JsonPipe } from '@angular/common';\nimport { RouterOutlet } from '@angular/router';\nimport { DummyApi, Flight } from 'sdk';\n\n@Component({\n selector: 'app-root',\n standalone: true,\n imports: [JsonPipe, RouterOutlet],\n templateUrl: './app.component.html',\n styleUrl: './app.component.scss'\n})\nexport class AppComponent {\n /** Title of the application */\n public title = 'tutorial-app';\n\n public readonly dummyApi = inject(DummyApi);\n\n public readonly flight = signal<Flight | undefined>(undefined);\n\n constructor() {\n this.loadDummyData();\n }\n\n async loadDummyData() {\n const dummyData = await this.dummyApi.dummyGet({});\n this.flight.set(dummyData);\n }\n}\n"
}
},
"app.config.ts": {
"file": {
"contents": "import { ApiFetchClient } from '@ama-sdk/client-fetch';\nimport { MockInterceptRequest, SequentialMockAdapter } from '@ama-sdk/core';\nimport { ApplicationConfig, provideZoneChangeDetection, importProvidersFrom } from '@angular/core';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport { provideRouter } from '@angular/router';\nimport { prefersReducedMotion } from '@o3r/application';\nimport { Serializer } from '@o3r/core';\nimport { ConsoleLogger, Logger, LOGGER_CLIENT_TOKEN, LoggerService } from '@o3r/logger';\nimport { StorageSync } from '@o3r/store-sync';\nimport { EffectsModule } from '@ngrx/effects';\nimport { RuntimeChecks, StoreModule } from '@ngrx/store';\nimport { DummyApi } from 'sdk';\nimport { OPERATION_ADAPTER } from 'sdk/spec';\nimport { routes } from './app.routes';\nimport { environment, additionalModules } from '../environments/environment';\n\nconst localStorageStates: Record<string, Serializer<any>>[] = [/* Store to register in local storage */];\nconst storageSync = new StorageSync({\n keys: localStorageStates, rehydrate: true\n});\n\nconst rootReducers = {\n \n};\n\nconst metaReducers = [storageSync.localStorageSync()];\nconst runtimeChecks: Partial<RuntimeChecks> = {\n strictActionImmutability: false,\n strictActionSerializability: false,\n strictActionTypeUniqueness: !environment.production,\n strictActionWithinNgZone: !environment.production,\n strictStateImmutability: !environment.production,\n strictStateSerializability: false\n};\n\nfunction dummyApiFactory(logger: Logger) {\n const apiConfig = new ApiFetchClient(\n {\n basePath: 'http://localhost:3000',\n requestPlugins: [\n new MockInterceptRequest({\n adapter: new SequentialMockAdapter(\n OPERATION_ADAPTER,\n {\n '/dummy_get': [{\n mockData: {\n originLocationCode: 'PAR',\n destinationLocationCode: 'NYC'\n }\n }]\n }\n )\n })\n ],\n fetchPlugins: [],\n logger\n }\n );\n return new DummyApi(apiConfig);\n}\n\nexport const appConfig: ApplicationConfig = {\n providers: [\n provideZoneChangeDetection({ eventCoalescing: true }),\n provideRouter(routes),\n importProvidersFrom(EffectsModule.forRoot([])),\n importProvidersFrom(StoreModule.forRoot(rootReducers, {metaReducers, runtimeChecks})),\n importProvidersFrom(additionalModules),\n importProvidersFrom(BrowserAnimationsModule.withConfig({disableAnimations: prefersReducedMotion()})),\n {provide: LOGGER_CLIENT_TOKEN, useValue: new ConsoleLogger()},\n {provide: DummyApi, useFactory: dummyApiFactory, deps: [LoggerService]}\n ]\n};\n"
}
}
}
}
}
}
}
}
}
}
}
}
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,2 @@
export * from './base';
export * from './core';
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
### 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.

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

> [!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,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';
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ function getFilesContent(resources: Resource[]) {
return (resources.reduce((fileSystemTree: FileSystemTree, resource) => {
const sanitizedPath = `./${resource.path.replace(new RegExp('^[.]/?'), '')}`;
const parsedPath = sanitizedPath.split('/').filter((pathEl) => !!pathEl);
overrideFileSystemTree(fileSystemTree, JSON.parse(resource.content) as FileSystemTree, parsedPath);
overrideFileSystemTree(fileSystemTree, JSON.parse(resource.content).fileSystemTree as FileSystemTree, parsedPath);
return fileSystemTree;
}, {} as FileSystemTree)['.'] as DirectoryNode).directory;
}
Expand Down
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
18 changes: 18 additions & 0 deletions packages/@o3r-training/training-sdk/.eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,24 @@ module.exports = {
'import/resolver': 'node'
},
'overrides': [
{
'files': ['*.ts'],
'rules': {
'@typescript-eslint/no-unused-vars': 'off',
'@typescript-eslint/naming-convention': 'off',
'@typescript-eslint/restrict-template-expressions': 'off',
'max-len': 'off',
'no-redeclare': 'off',
'no-use-before-define': 'off',
'no-useless-escape': 'off'
}
},
{
'files': ['*.jasmine.fixture.ts', '*api.fixture.ts'],
'rules': {
'jest/no-jasmine-globals': 'off'
}
},
{
'files': ['*.helper.ts'],
'rules': {
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 @@ -17,6 +17,10 @@ paths:
responses:
200:
description: "Successful operation"
content:
application/json:
schema:
$ref: '#/components/schemas/Flight'
components:
schemas:
Flight:
Expand Down
Loading

0 comments on commit 558242b

Please sign in to comment.