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/module app/appsettings/getter #2577

Open
wants to merge 12 commits into
base: main
Choose a base branch
from
Open
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
43 changes: 43 additions & 0 deletions .changeset/large-beds-jog.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
---
'@equinor/fusion-framework-module-app': minor
'@equinor/fusion-framework-react-app': minor
---

#### Changes:

1. **AppClient.ts**
- Added `updateAppSettings` method to set app settings by appKey.

2. **AppModuleProvider.ts**
- Added `updateAppSettings` method to update app settings.

3. **App.ts**
- Added `updateSettings` and `updateSettingsAsync` methods to set app settings.
- Added effects to monitor and dispatch events for settings updates.

4. **actions.ts**
- Added `updateSettings` async action for updating settings.

5. **create-reducer.ts**
- Added reducer case for `updateSettings.success` to update state settings.

6. **create-state.ts**
- Added `handleUpdateSettings` flow to handle updating settings.

7. **events.ts**
- Added new events: `onAppSettingsUpdate`, `onAppSettingsUpdated`, and `onAppSettingsUpdateFailure`.

8. **flows.ts**
- Added `handleUpdateSettings` flow to handle the set settings action.

9. **package.json**
- Added `settings` entry to exports and types.

10. **index.ts**
- Created new file to export `useAppSettings`.

11. **useAppSettings.ts**
- Created new hook for handling app settings.

12. **app-proxy-plugin.ts**
- Add conditional handler for persons/me/appKey/settings to prevent matching against appmanifest path
42 changes: 28 additions & 14 deletions cookbooks/app-react/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,30 @@
export const App = () => (
<div
style={{
height: '100%',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
background: '#f0f0f0',
color: '#343434',
}}
>
<h1>🚀 Hello Fusion 😎</h1>
</div>
);
import { useAppSettings } from '@equinor/fusion-framework-react-app/settings';
import { useCallback } from 'react';

export const App = () => {
const { settings, updateSettings } = useAppSettings();

console.log('settings', settings);

const updateSettingsCallback = useCallback(() => {
updateSettings({ theme: 'dark', date: new Date().toISOString() });
}, []);

return (
<div
style={{
height: '100%',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
background: '#f0f0f0',
color: '#343434',
}}
>
<h1>🚀 Hello Fusion 😎</h1>
<button onClick={updateSettingsCallback}>SetSettings</button>
</div>
);
};

export default App;
13 changes: 10 additions & 3 deletions packages/cli/src/lib/plugins/app-proxy/app-proxy-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,9 +161,16 @@ export const appProxyPlugin = (options: AppProxyPluginOptions): Plugin => {

// serve app manifest if request matches the current app
const manifestPath = [proxyPath, app.manifestPath ?? `apps/${app.key}`].join('/');
server.middlewares.use(manifestPath, async (_req, res) => {
res.setHeader('content-type', 'application/json');
res.end(JSON.stringify(await app.generateManifest()));
server.middlewares.use(async (req, res, next) => {
// We only want to match the exact path
const [requestPath] = (req.url ?? '').split('?');
if (requestPath === manifestPath) {
res.setHeader('content-type', 'application/json');
res.end(JSON.stringify(await app.generateManifest()));
return;
}

next();
});

// serve local bundles if request matches the current app and version
Expand Down
1 change: 1 addition & 0 deletions packages/modules/app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
"@equinor/fusion-query": "workspace:^",
"immer": "^9.0.16",
"rxjs": "^7.8.1",
"uuid": "^11.0.3",
"zod": "^3.23.8"
},
"devDependencies": {
Expand Down
83 changes: 79 additions & 4 deletions packages/modules/app/src/AppClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ import { jsonSelector } from '@equinor/fusion-framework-module-http/selectors';

import { ApiApplicationSchema } from './schemas';

import type { AppConfig, AppManifest, ConfigEnvironment } from './types';
import { AppConfigError, AppManifestError } from './errors';
import type { AppConfig, AppManifest, AppSettings, ConfigEnvironment } from './types';
import { AppConfigError, AppManifestError, AppSettingsError } from './errors';
import { AppConfigSelector } from './AppClient.Selectors';

export interface IAppClient extends Disposable {
Expand All @@ -30,6 +30,21 @@ export interface IAppClient extends Disposable {
appKey: string;
tag?: string;
}) => ObservableInput<AppConfig<TType>>;

/**
* Fetch app settings by appKey
*/
getAppSettings: (args: { appKey: string }) => ObservableInput<AppSettings>;

/**
* Set app settings by appKey
* @param args - Object with appKey and settings
* @returns ObservableInput<AppSettings>
*/
updateAppSettings: (args: {
appKey: string;
settings: AppSettings;
}) => ObservableInput<AppSettings>;
}

/**
Expand Down Expand Up @@ -62,6 +77,7 @@ export class AppClient implements IAppClient {
#manifest: Query<AppManifest, { appKey: string }>;
#manifests: Query<AppManifest[], { filterByCurrentUser?: boolean } | undefined>;
#config: Query<AppConfig, { appKey: string; tag?: string }>;
#settings: Query<AppSettings, { appKey: string; settings?: AppSettings }>;

constructor(client: IHttpClient) {
const expire = 1 * 60 * 1000;
Expand Down Expand Up @@ -90,8 +106,8 @@ export class AppClient implements IAppClient {
'Api-Version': '1.0',
},
selector: async (res: Response) => {
const response = (await jsonSelector(res)) as { value: unknown[] };
return ApplicationSchema.array().parse(response.value);
const body = await res.json();
return body;
},
});
},
Expand All @@ -114,7 +130,31 @@ export class AppClient implements IAppClient {
key: (args) => JSON.stringify(args),
expire,
});

this.#settings = new Query<AppSettings, { appKey: string; settings?: AppSettings }>({
client: {
fn: ({ appKey, settings }) => {
// is settings construct a push request
const update = settings
? { method: 'PUT', body: JSON.stringify(settings) }
: {};

return client.json(`/persons/me/apps/${appKey}/settings`, {
headers: {
'Api-Version': '1.0',
},
...update,
selector: async (res: Response) => {
return res.json();
},
});
},
},
key: (args) => JSON.stringify(args),
expire,
});
}

getAppManifest(args: { appKey: string }): Observable<AppManifest> {
return this.#manifest.query(args).pipe(
queryValue,
Expand Down Expand Up @@ -158,11 +198,46 @@ export class AppClient implements IAppClient {
);
}

getAppSettings(args: { appKey: string }): Observable<AppSettings> {
return this.#settings.query(args).pipe(
queryValue,
catchError((err) => {
/** extract cause, since error will be a `QueryError` */
const { cause } = err;
if (cause instanceof AppSettingsError) {
throw cause;
}
if (cause instanceof HttpResponseError) {
throw AppSettingsError.fromHttpResponse(cause.response, { cause });
}
throw new AppSettingsError('unknown', 'failed to load settings', { cause });
}),
);
}

updateAppSettings(args: { appKey: string; settings: AppSettings }): Observable<AppSettings> {
return this.#settings.query(args).pipe(
queryValue,
catchError((err) => {
/** extract cause, since error will be a `QueryError` */
const { cause } = err;
if (cause instanceof AppSettingsError) {
throw cause;
}
if (cause instanceof HttpResponseError) {
throw AppSettingsError.fromHttpResponse(cause.response, { cause });
}
throw new AppSettingsError('unknown', 'failed to update app settings', { cause });
}),
);
}

[Symbol.dispose]() {
console.warn('AppClient disposed');
this.#manifest.complete();
this.#manifests.complete();
this.#config.complete();
this.#settings.complete();
}
}

Expand Down
19 changes: 18 additions & 1 deletion packages/modules/app/src/AppModuleProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
import { ModuleType } from '@equinor/fusion-framework-module';
import { EventModule } from '@equinor/fusion-framework-module-event';

import type { AppConfig, AppManifest, ConfigEnvironment, CurrentApp } from './types';
import type { AppConfig, AppManifest, AppSettings, ConfigEnvironment, CurrentApp } from './types';

import { App, filterEmpty, IApp } from './app/App';
import { AppModuleConfig } from './AppConfigurator';
Expand Down Expand Up @@ -122,6 +122,23 @@ export class AppModuleProvider {
return from(this.#appClient.getAppConfig<TType>({ appKey, tag }));
}

/**
* fetch user settings for an application
* @param appKey - application key
*/
public getAppSettings(appKey: string): Observable<AppSettings> {
return from(this.#appClient.getAppSettings({ appKey }));
}

/**
* Put user settings for an application
* @param appKey - application key
* @param settings - The settings to add save
*/
public updateAppSettings(appKey: string, settings: AppSettings): Observable<AppSettings> {
return from(this.#appClient.updateAppSettings({ appKey, settings }));
}

/**
* set the current application, will internally resolve manifest
* @param appKey - application key
Expand Down
Loading
Loading