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: add indep bff doc #6803

Merged
merged 3 commits into from
Feb 18, 2025
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: 8 additions & 0 deletions .changeset/bright-apricots-complain.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'@modern-js/create-request': patch
'@modern-js/main-doc': patch
'@modern-js/plugin-bff': patch
---

feat: BFF 跨项目调用支持配置域名,补充文档
feat: BFF cross-project-invocation supports configuration of domain, add doc
7 changes: 4 additions & 3 deletions packages/cli/plugin-bff/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ export const bffPlugin = (): CliPlugin<AppTools> => ({

const handleCrossProjectInvocation = async (isBuild = false) => {
const { bff } = api.useResolvedConfigContext();
if (bff?.enableCrossProjectInvocation) {
if (bff?.crossProject) {
if (!isBuild) {
await compileApi();
}
Expand Down Expand Up @@ -242,7 +242,7 @@ export const bffPlugin = (): CliPlugin<AppTools> => ({
const appContext = api.useAppContext();
const config = api.useResolvedConfigContext();

if (config?.bff?.enableCrossProjectInvocation) {
if (config?.bff?.crossProject) {
return [appContext.apiDirectory];
} else {
return [];
Expand All @@ -260,7 +260,8 @@ export const bffPlugin = (): CliPlugin<AppTools> => ({
if (
!isPrivate &&
(eventType === 'change' || eventType === 'unlink') &&
filename.startsWith(`${relativeApiPath}/`)
filename.startsWith(`${relativeApiPath}/`) &&
(filename.endsWith('.ts') || filename.endsWith('.js'))
) {
await handleCrossProjectInvocation();
}
Expand Down
131 changes: 89 additions & 42 deletions packages/cli/plugin-bff/src/utils/clientGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,14 @@ interface FileDetails {
relativeTargetDistDir: string;
exportKey: string;
}
const API_DIR = 'api';
const PLUGIN_DIR = 'plugin';
const RUNTIME_DIR = 'runtime';
const CLIENT_DIR = 'client';

const EXPORT_PREFIX = `./${API_DIR}/`;
const TYPE_PREFIX = `${API_DIR}/`;

export async function readDirectoryFiles(
appDirectory: string,
directory: string,
Expand All @@ -48,7 +56,7 @@ export async function readDirectoryFiles(
const parsedPath = path.parse(relativePath);

const targetDir = path.join(
`./${relativeDistPath}/client`,
`./${relativeDistPath}/${CLIENT_DIR}`,
parsedPath.dir,
`${parsedPath.name}.js`,
);
Expand Down Expand Up @@ -83,6 +91,31 @@ export async function readDirectoryFiles(
return filesList;
}

function mergePackageJson(
packageJson: any,
files: string[],
typesVersion: Record<string, any>,
exports: Record<string, any>,
) {
packageJson.files = [...new Set([...(packageJson.files || []), ...files])];

packageJson.typesVersions ??= {};
const starTypes = packageJson.typesVersions['*'] || {};
Object.keys(starTypes).forEach(
k => k.startsWith(TYPE_PREFIX) && delete starTypes[k],
);
packageJson.typesVersions['*'] = {
...starTypes,
...(typesVersion['*'] || {}),
};

packageJson.exports ??= {};
Object.keys(packageJson.exports).forEach(
k => k.startsWith(EXPORT_PREFIX) && delete packageJson.exports[k],
);
Object.assign(packageJson.exports, exports);
}

async function writeTargetFile(absTargetDir: string, content: string) {
await fs.mkdir(path.dirname(absTargetDir), { recursive: true });
await fs.writeFile(absTargetDir, content);
Expand All @@ -96,51 +129,60 @@ async function setPackage(
}[],
appDirectory: string,
relativeDistPath: string,
relativeApiPath: string,
) {
try {
const packagePath = path.resolve(appDirectory, './package.json');
const packageContent = await fs.readFile(packagePath, 'utf8');
const packageJson = JSON.parse(packageContent);

packageJson.exports = packageJson.exports || {};
packageJson.typesVersions = packageJson.typesVersions || { '*': {} };

files.forEach(file => {
const exportKey = `./api/${file.exportKey}`;
const jsFilePath = `./${file.targetDir}`;
const typePath = file.relativeTargetDistDir;

packageJson.exports[exportKey] = {
import: jsFilePath,
types: typePath,
};

packageJson.typesVersions['*'][`api/${file.exportKey}`] = [typePath];
});
const addFiles = [
`${relativeDistPath}/${CLIENT_DIR}/**/*`,
`${relativeDistPath}/${RUNTIME_DIR}/**/*`,
`${relativeDistPath}/${PLUGIN_DIR}/**/*`,
];

packageJson.exports['./plugin'] = {
require: `./${relativeDistPath}/plugin/index.js`,
types: `./${relativeDistPath}/plugin/index.d.ts`,
const typesVersions = {
'*': files.reduce(
(acc, file) => {
const typeFilePath = `./${file.targetDir}`.replace('js', 'd.ts');
return {
...acc,
[`${TYPE_PREFIX}${file.exportKey}`]: [typeFilePath],
};
},
{
[RUNTIME_DIR]: [`./${relativeDistPath}/${RUNTIME_DIR}/index.d.ts`],
[PLUGIN_DIR]: [`./${relativeDistPath}/${PLUGIN_DIR}/index.d.ts`],
},
),
};

packageJson.exports['./runtime'] = {
import: `./${relativeDistPath}/runtime/index.js`,
types: `./${relativeDistPath}/runtime/index.d.ts`,
};
packageJson.typesVersions['*'].runtime = [
`./${relativeDistPath}/runtime/index.d.ts`,
];
packageJson.typesVersions['*'].plugin = [
`./${relativeDistPath}/plugin/index.d.ts`,
];
const exports = files.reduce(
(acc, file) => {
const exportKey = `${EXPORT_PREFIX}${file.exportKey}`;
const jsFilePath = `./${file.targetDir}`;

packageJson.files = [
`./${relativeDistPath}/client/**/*`,
`./${relativeDistPath}/${relativeApiPath}/**/*`,
`./${relativeDistPath}/runtime/**/*`,
`./${relativeDistPath}/plugin/**/*`,
];
return {
...acc,
[exportKey]: {
import: jsFilePath,
types: jsFilePath.replace(/\.js$/, '.d.ts'),
},
};
},
{
[`./${PLUGIN_DIR}`]: {
require: `./${relativeDistPath}/${PLUGIN_DIR}/index.js`,
types: `./${relativeDistPath}/${PLUGIN_DIR}/index.d.ts`,
},
[`./${RUNTIME_DIR}`]: {
import: `./${relativeDistPath}/${RUNTIME_DIR}/index.js`,
types: `./${relativeDistPath}/${RUNTIME_DIR}/index.d.ts`,
},
},
);

mergePackageJson(packageJson, addFiles, typesVersions, exports);

await fs.promises.writeFile(
packagePath,
Expand All @@ -151,6 +193,12 @@ async function setPackage(
}
}

export async function copyFiles(from: string, to: string) {
if (await fs.pathExists(from)) {
await fs.copy(from, to);
}
}

async function clientGenerator(draftOptions: APILoaderOptions) {
const sourceList = await readDirectoryFiles(
draftOptions.appDir,
Expand Down Expand Up @@ -197,19 +245,18 @@ async function clientGenerator(draftOptions: APILoaderOptions) {
const code = await getClitentCode(source.resourcePath, source.source);
if (code?.value) {
await writeTargetFile(source.absTargetDir, code.value);
await copyFiles(
source.relativeTargetDistDir,
source.targetDir.replace(`js`, 'd.ts'),
);
}
}
logger.info(`Client bundle generate succeed`);
} catch (error) {
logger.error(`Client bundle generate failed: ${error}`);
}

setPackage(
sourceList,
draftOptions.appDir,
draftOptions.relativeDistPath,
draftOptions.relativeApiPath,
);
setPackage(sourceList, draftOptions.appDir, draftOptions.relativeDistPath);
}

export default clientGenerator;
4 changes: 4 additions & 0 deletions packages/cli/plugin-bff/src/utils/runtimeGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ async function runtimeGenerator({
request?: F;
interceptor?: (request: F) => F;
allowedHeaders?: string[];
setDomain?: (ops?: {
target: 'node' | 'browser';
requestId: string;
}) => string;
requestId?: string;
};
export declare const configure: (options: IOptions) => void;`;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
1. run `@modern-js/create` command:

```bash
npx @modern-js/create@latest myapi
```

2. interactive Q & A interface to initialize the project based on the results, with initialization performed according to the default settings:

```bash
? Please select the programming language: TS
? Please select the package manager: pnpm
```

3. Execute the `new` command,enable BFF:

```bash
? Please select the operation you want to perform Enable optional features
? Please select the feature to enable Enable "BFF"
? Please select BFF type Framework mode
```


4. Execute【[Existing BFF-enabled Projects](/en/guides/advanced-features/bff/cross-project.html#existing-bff-enabled-projects)】to turn on the cross-project call switch.

**Note:** When a project serves solely as a BFF producer, its runtime does not depend on the `/src` source directory. Removing the `/src` directory can help optimize the project's build efficiency.
Original file line number Diff line number Diff line change
@@ -1 +1 @@
["function", "frameworks", "extend-server", "sdk", "upload"]
["function", "frameworks", "extend-server", "sdk", "upload", "cross-project"]
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import { PackageManagerTabs } from '@theme';

# Cross-Project Invocation

Based on the BFF architecture, Modern.js provides cross-project invocation capabilities, allowing BFF functions created in one project to be invoked by other projects through integrated calls, enabling function sharing and feature reuse across projects.
Cross-project invocation consists of **producer** and **consumer** sides. The producer is responsible for creating and providing BFF services while generating integrated invocation SDK, and the consumer initiates requests through these SDK.

## BFF Producer

Upgrade Modern.js dependencies to version x.64.4 or higher, then enable cross-project invocation via configuration. Projects with BFF capabilities enabled can act as BFF producers, or you can create standalone BFF applications.
When executing `dev` or `build`, the following artifacts for consumers will be automatically generated:
- API functions under the `dist/client` directory
- Runtime configuration functions under the `dist/runtime` directory
- Interface exports defined in `exports` field of `package.json`
- File list for npm publication specified in `files` field of `package.json`

### Existing BFF-enabled Projects

1. Enable Cross-Project Invocation

Ensure the current project has BFF enabled with API files defined under `api/lambda`. Add the following configuration:

```ts title="modern.config.ts"
export default defineConfig({
bff: {
crossProject: true,
}
});
```

2. Generate SDK Type Files

To provide type hints for the integrated invocation SDK, enable the `declaration` option in TypeScript configuration:

```ts title="tsconfig.json"
"compilerOptions": {
"declaration": true,
}
```

### Create BFF Application

import CreateApi from "@site-docs-en/components/create-bff-api-app"

<CreateApi/>

## BFF Consumer

:::info
You can initiate requests to BFF producers from projects using any framework via the SDK.
:::

### Intra-Monorepo Invocation

When producer and consumer are in the same Monorepo, directly import the SDK. API functions reside under `${package_name}/api`:

```ts title="src/routes/page.tsx"
import { useState, useEffect } from 'react';
import { get as hello } from '${package_name}/api/hello';

export default () => {
const [text, setText] = useState('');

useEffect(() => {
hello().then(setText);
}, []);
return <div>{text}</div>;
};
```

### Cross-Project Invocation

When producer and consumer are in separate repositories, publish the BFF producer as an npm package. The invocation method remains the same as intra-Monorepo.

### Domain Configuration and Extensions

For real-world scenarios requiring custom BFF service domains, use the configuration function:

```ts title="src/routes/page.tsx"
import { configure } from '${package_name}/runtime';

configure({
setDomain() {
return 'https://your-bff-api.com';
},
});
```

The `configure` function from `${package_name}/runtime` supports domain configuration via `setDomain`, interceptors, and custom SDK. When extending both **current project** and **cross-project** SDK on the same page:

```ts title="src/routes/page.tsx"
import { configure } from '${package_name}/runtime';
import { configure as innerConfigure } from '@modern-js/runtime/bff';
import axios from 'axios';

configure({
setDomain() {
return 'https://your-bff-api.com';
},
});

innerConfigure({
async request(...config: Parameters<typeof fetch>) {
const [url, params] = config;
const res = await axios({
url: url as string,
method: params?.method as Method,
data: params?.body,
headers: {
'x-header': 'innerConfigure',
},
});
return res.data;
},
});
```
Loading
Loading