Skip to content
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
78 changes: 78 additions & 0 deletions apps/web/cli/api-doc-gen.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import fs from 'fs';
import path from 'path';

const API_DIR = './src/api-clients';
const OUTPUT_PATH = './src/api-clients/_common/constants/api-doc.ts';


const generateAPIDocumentation = (basePath) => {
const result = {};

const traverse = (dirPath) => {
const parts = dirPath.split(path.sep).slice(-5);
if (parts.length !== 5) return;
if (parts[3] !== 'api-verbs' || parts[1] === '_common') return;

const [serviceName, resourceName, , , verb] = parts;

if (!result[serviceName]) result[serviceName] = {};
if (!result[serviceName][resourceName]) result[serviceName][resourceName] = [];

result[serviceName][resourceName].push(verb.replace('.ts', ''));
};

const walk = (currentPath) => {
const files = fs.readdirSync(currentPath);

files.forEach((file) => {
const fullPath = path.join(currentPath, file);

const stat = fs.statSync(fullPath);

if (stat.isDirectory()) {
walk(fullPath);
} else if (file.endsWith('.ts')) {
traverse(fullPath);
}
});
};

walk(basePath);
return result;
};

const API_DOC = generateAPIDocumentation(API_DIR);

const tsContent = `/**
* 🚀 AUTO-GENERATED API DOCUMENTATION
*
* This file is **automatically generated** by the API documentation script.
* **DO NOT** modify this file manually, as changes will be overwritten.
*
* ## Purpose:
* - Provides a structured mapping of API endpoints based on the directory structure.
* - Used for **query key generation**, **caching strategies**, and **API reference**.
* - Helps maintain consistency and prevents hardcoded API keys.
*
* ## How It Works:
* - The script scans the \`api-clients/{service-name}/{resource-name}/schema/api-verbs/\` directory.
* - Extracts \`{service-name}\`, \`{resource-name}\`, and \`{verb}.ts\` files.
* - Generates a structured **API_DOC** constant.
*
* ## Regenerate:
* If you need to update this file, run:
*
* \`\`\`sh
* npm run api-doc
* \`\`\`
*
* 🚨 Any manual modifications will be lost on regeneration!
*/

export const API_DOC = ${JSON.stringify(API_DOC, null, 4)} as const;
export type APIDoc = typeof API_DOC;
`;
fs.writeFileSync(OUTPUT_PATH, tsContent);


console.log('✅ API Keys generated successfully!');
3 changes: 2 additions & 1 deletion apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
"eslint:fix": "eslint --fix --ext .js,.vue,.ts .",
"stylelint:fix": "stylelint --fix \"src/**/*.{css,vue,pcss,scss}\"",
"format": "npm run eslint:fix && npm run stylelint:fix",
"postcss": "node build/reset-css.js"
"postcss": "node build/reset-css.js",
"api-doc": "node ./cli/api-doc-gen.js && npx eslint ./src/api-clients/_common/constants/api-doc.ts --fix"
},
"main": "dist/cloudforet-component.common.js",
"dependencies": {
Expand Down
59 changes: 59 additions & 0 deletions apps/web/src/api-clients/_common/composables/use-api-query-key.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import type { ComputedRef } from 'vue';
import { computed, reactive } from 'vue';


import type { QueryKey } from '@tanstack/vue-query';

import type {
ResourceName, ServiceName, Verb,
} from '@/api-clients/_common/types/query-key-type';


import { useAppContextStore } from '@/store/app-context/app-context-store';
import { useUserWorkspaceStore } from '@/store/app-context/workspace/user-workspace-store';

/**
* Generates a computed query key for API requests, incorporating global parameters.
*
* @param service - The service name, representing the API service scope (e.g., 'dashboard').
* @param resource - The resource name, specifying the target API resource (e.g., 'public-data-table').
* @param verb - The API action verb, defining the type of request (e.g., 'get', 'list', 'update').
* @param additionalGlobalParams - Optional additional global parameters (e.g., workspace ID, admin mode).
* @returns A computed reference to the query key array, structured as `[service, resource, verb, { globalParams }]`.
*
* ### Example Usage:
* ```ts
* const queryKey = useAPIQueryKey('dashboard', 'public-data-table', 'get');
* ```
* The generated query key ensures:
* - **Type safety**: Prevents invalid API calls by enforcing a valid `service/resource/verb` combination.
* - **Auto-completion**: Provides intelligent suggestions based on predefined API structure.
* - **Cache management**: Enables precise cache invalidation and data synchronization.
*/

interface GlobalQueryParams {
workspaceId?: string;
isAdminMode?: boolean;
}
export const useAPIQueryKey = <S extends ServiceName, R extends ResourceName<S>, V extends Verb<S, R>>(
service: S,
resource: R,
verb: V,
additionalGlobalParams?: Partial<GlobalQueryParams>,
): ComputedRef<QueryKey> => {
const appContextStore = useAppContextStore();
const userWorkspaceStore = useUserWorkspaceStore();

const _state = reactive({
currentWorkdpaceId: computed<string|undefined>(() => userWorkspaceStore.getters.currentWorkspaceId),
isAdminMode: computed<boolean>(() => appContextStore.getters.isAdminMode),
});

const globalQueryParams = reactive<GlobalQueryParams>({
workspaceId: _state.currentWorkdpaceId,
isAdminMode: _state.isAdminMode,
...additionalGlobalParams,
});

return computed<QueryKey>(() => [service, resource, verb, { ...globalQueryParams }]);
};
41 changes: 0 additions & 41 deletions apps/web/src/api-clients/_common/composables/use-query-key.ts

This file was deleted.

199 changes: 199 additions & 0 deletions apps/web/src/api-clients/_common/constants/api-doc.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
/**
* 🚀 AUTO-GENERATED API DOCUMENTATION
*
* This file is **automatically generated** by the API documentation script.
* **DO NOT** modify this file manually, as changes will be overwritten.
*
* ## Purpose:
* - Provides a structured mapping of API endpoints based on the directory structure.
* - Used for **query key generation**, **caching strategies**, and **API reference**.
* - Helps maintain consistency and prevents hardcoded API keys.
*
* ## How It Works:
* - The script scans the `api-clients/{service-name}/{resource-name}/schema/api-verbs/` directory.
* - Extracts `{service-name}`, `{resource-name}`, and `{verb}.ts` files.
* - Generates a structured **API_DOC** constant.
*
* ## Regenerate:
* If you need to update this file, run:
*
* ```sh
* npm run api-doc
* ```
*
* 🚨 Any manual modifications will be lost on regeneration!
*/

export const API_DOC = {
'cost-analysis': {
budget: [
'create',
'delete',
'get',
'list',
'set-notification',
'update',
],
'budget-usage': [
'analyze',
'list',
],
cost: [
'analyze',
'stat',
],
'cost-query-set': [
'create',
'delete',
'list',
'update',
],
'cost-report': [
'get-url',
'get',
'list',
'send',
],
'cost-report-config': [
'list',
'update-recipients',
'update',
],
'cost-report-data': [
'analyze',
'list',
],
'data-source': [
'get',
'list',
'sync',
'update-permissions',
],
'data-source-account': [
'analyze',
'list',
'reset',
'update',
],
job: [
'cancel',
'list',
],
'unified-cost': [
'analyze',
'get',
'list',
'stat',
],
},
dashboard: {
'private-dashboard': [
'change-folder',
'create',
'delete',
'get',
'list',
'update',
],
'private-data-table': [
'add',
'delete',
'get',
'list',
'load',
'transform',
'update',
],
'private-folder': [
'create',
'delete',
'get',
'list',
'update',
],
'private-widget': [
'create',
'delete',
'get',
'list',
'load-sum',
'load',
'update',
],
'public-dashboard': [
'change-folder',
'create',
'delete',
'get',
'list',
'share',
'unshare',
'update',
],
'public-data-table': [
'add',
'delete',
'get',
'list',
'load',
'transform',
'update',
],
'public-folder': [
'create',
'delete',
'get',
'list',
'share',
'unshare',
'update',
],
'public-widget': [
'create',
'delete',
'get',
'list',
'load-sum',
'load',
'update',
],
},
opsflow: {
comment: [
'create',
'delete',
'get',
'list',
'update',
],
event: [
'list',
],
task: [
'change-assignee',
'change-status',
'create',
'delete',
'get',
'list',
'update-description',
'update',
],
'task-category': [
'create',
'delete',
'get',
'list',
'update',
],
'task-type': [
'create',
'delete',
'get',
'list',
'update-fields',
'update',
],
},
} as const;
export type APIDoc = typeof API_DOC;
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Question] Great implementation! Since API_DOC is only used for type inference and isn’t referenced anywhere else, it won’t affect runtime performance due to Vite’s tree shaking.

Just curious—did you consider defining APIDoc directly as a TypeScript type without creating the API_DOC object? It would achieve the same type safety and autocomplete without creating a constant, even if it’s tree-shaken. Not a required change, just wanted to know your thoughts! 😊

--
[Question] 좋은 구현이네요! API_DOC이 타입 추론용으로만 사용되고 다른 곳에서는 참조되지 않기 때문에, Vite의 트리 쉐이킹 덕분에 런타임 성능에 영향을 주지 않을 거라는 점도 확인했습니다.

그런데 혹시 API_DOC 객체를 생성하지 않고 TypeScript 타입으로만 APIDoc을 정의하는 방법도 고려해보셨나요? 이렇게 하면 (트리 쉐이킹과 관계없이) 상수를 만들지 않고도 동일한 타입 안정성과 자동 완성을 얻을 수 있습니다. 꼭 바꿀 필요는 없고, 단지 의견이 궁금해서 여쭤봅니다! 😊

Loading
Loading