plugin-block-cross-join 0.1.6 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -29,6 +29,7 @@ __export(cross_join_query_exports, {
29
29
  crossJoinQuery: () => crossJoinQuery
30
30
  });
31
31
  module.exports = __toCommonJS(cross_join_query_exports);
32
+ var import_acl = require("@nocobase/acl");
32
33
  function toPlainObject(row) {
33
34
  if (row && typeof row.toJSON === "function") {
34
35
  return row.toJSON();
@@ -39,10 +40,9 @@ function buildJoinMap(rows, keyField) {
39
40
  const map = /* @__PURE__ */ new Map();
40
41
  for (const row of rows) {
41
42
  const key = String(row[keyField] ?? "");
42
- if (!map.has(key)) {
43
- map.set(key, []);
44
- }
45
- map.get(key).push(row);
43
+ const matches = map.get(key) || [];
44
+ matches.push(row);
45
+ map.set(key, matches);
46
46
  }
47
47
  return map;
48
48
  }
@@ -112,14 +112,58 @@ async function crossJoinQuery(ctx, next) {
112
112
  if (!primaryRepo) {
113
113
  ctx.throw(400, `Collection "${primarySource.collection}" not found in datasource "${primarySource.dataSource}"`);
114
114
  }
115
+ const sources = [primarySource, ...joins];
116
+ const permissions = await Promise.all(
117
+ sources.map(async (source, index) => {
118
+ var _a, _b;
119
+ const dataSource = dsManager.get(source.dataSource);
120
+ if (!(dataSource == null ? void 0 : dataSource.acl)) ctx.throw(403);
121
+ const permissionContext = Object.create(ctx);
122
+ Object.defineProperties(permissionContext, {
123
+ dataSource: { value: dataSource },
124
+ database: { value: dataSource.collectionManager.db }
125
+ });
126
+ const resolved = await dataSource.acl.resolveActionParams(permissionContext, {
127
+ resourceName: source.collection,
128
+ actionName: "list",
129
+ params: index === 0 ? { filter: primarySource.filter || {}, sort: sort || config.defaultSort } : {}
130
+ }).catch((error) => {
131
+ if (error instanceof import_acl.NoPermissionError) ctx.throw(403);
132
+ throw error;
133
+ });
134
+ const fields = (_a = resolved.parsedParams) == null ? void 0 : _a.fields;
135
+ const except = ((_b = resolved.parsedParams) == null ? void 0 : _b.except) || [];
136
+ const assertField = (field) => {
137
+ const name = field.replace(/^[+-]/, "").split(".")[0];
138
+ if (fields && !fields.includes(name) || except.includes(name)) ctx.throw(403);
139
+ };
140
+ columns.filter((column) => column.source === index).forEach((column) => assertField(column.field));
141
+ if (index === 0) {
142
+ joins.forEach((join) => assertField(join.leftField));
143
+ const requestedSort = sort || config.defaultSort || [];
144
+ (Array.isArray(requestedSort) ? requestedSort : [requestedSort]).forEach(assertField);
145
+ const checkFilter = (filter) => {
146
+ if (!filter || typeof filter !== "object") return;
147
+ for (const [key, value] of Object.entries(filter)) {
148
+ if (key.startsWith("$") || Array.isArray(filter)) checkFilter(value);
149
+ else assertField(key);
150
+ }
151
+ };
152
+ checkFilter(primarySource.filter);
153
+ } else {
154
+ assertField(joins[index - 1].rightField);
155
+ }
156
+ return resolved.mergedParams;
157
+ })
158
+ );
115
159
  const hasInnerJoin = joins.some((j) => j.joinType === "inner");
116
160
  let primaryRows;
117
161
  let totalPrimaryCount;
118
162
  if (hasInnerJoin) {
119
163
  const MAX_ROWS = 1e4;
120
164
  const rawRows = await primaryRepo.find({
121
- filter: primarySource.filter || {},
122
- sort: sort || config.defaultSort,
165
+ ...permissions[0],
166
+ context: ctx,
123
167
  limit: MAX_ROWS
124
168
  });
125
169
  primaryRows = rawRows.map(toPlainObject);
@@ -127,13 +171,14 @@ async function crossJoinQuery(ctx, next) {
127
171
  } else {
128
172
  const [rawRows, count] = await Promise.all([
129
173
  primaryRepo.find({
130
- filter: primarySource.filter || {},
131
- sort: sort || config.defaultSort,
174
+ ...permissions[0],
175
+ context: ctx,
132
176
  limit: Number(pageSize),
133
177
  offset: (Number(page) - 1) * Number(pageSize)
134
178
  }),
135
179
  primaryRepo.count({
136
- filter: primarySource.filter || {}
180
+ filter: permissions[0].filter,
181
+ context: ctx
137
182
  })
138
183
  ]);
139
184
  primaryRows = rawRows.map(toPlainObject);
@@ -157,8 +202,10 @@ async function crossJoinQuery(ctx, next) {
157
202
  continue;
158
203
  }
159
204
  const joinRawRows = await joinRepo.find({
205
+ ...permissions[i + 1],
206
+ context: ctx,
160
207
  filter: {
161
- [joinDef.rightField]: { $in: distinctKeys.map(String) }
208
+ $and: [permissions[i + 1].filter || {}, { [joinDef.rightField]: { $in: distinctKeys.map(String) } }]
162
209
  },
163
210
  limit: 1e4
164
211
  });
@@ -177,12 +224,10 @@ async function crossJoinQuery(ctx, next) {
177
224
  }
178
225
  const finalRows = columns.length > 0 ? applyColumnMapping(paginatedRows, columns) : paginatedRows;
179
226
  ctx.body = {
180
- data: finalRows,
181
- meta: {
182
- page: Number(page),
183
- pageSize: Number(pageSize),
184
- count: totalCount
185
- }
227
+ rows: finalRows,
228
+ page: Number(page),
229
+ pageSize: Number(pageSize),
230
+ count: totalCount
186
231
  };
187
232
  await next();
188
233
  }
@@ -44,10 +44,17 @@ var import_server = require("@nocobase/server");
44
44
  var import_cross_join_query = require("./actions/cross-join-query");
45
45
  var import_path = __toESM(require("path"));
46
46
  class PluginBlockCrossJoinServer extends import_server.Plugin {
47
+ hotReloadMeta = {
48
+ supported: true
49
+ };
47
50
  async beforeLoad() {
48
- await this.db.import({ directory: import_path.default.resolve(__dirname, "collections") });
51
+ var _a;
52
+ if (!((_a = this.options) == null ? void 0 : _a.hotReloading)) {
53
+ await this.db.import({ directory: import_path.default.resolve(__dirname, "collections") });
54
+ }
49
55
  }
50
56
  async load() {
57
+ var _a;
51
58
  this.app.resourcer.define({
52
59
  name: "crossJoin",
53
60
  actions: {
@@ -55,11 +62,18 @@ class PluginBlockCrossJoinServer extends import_server.Plugin {
55
62
  }
56
63
  });
57
64
  this.app.acl.allow("crossJoin", "query", "loggedIn");
65
+ if (!((_a = this.options) == null ? void 0 : _a.hotReloading)) {
66
+ this.app.resourcer.registerPreActionHandler("crossJoin:query", async (_ctx, next) => {
67
+ await next();
68
+ });
69
+ }
58
70
  this.app.acl.registerSnippet({
59
71
  name: "ui.crossJoin",
60
72
  actions: ["crossJoin:*"]
61
73
  });
62
74
  }
75
+ async beforeHotReload() {
76
+ }
63
77
  }
64
78
  var plugin_default = PluginBlockCrossJoinServer;
65
79
  // Annotate the CommonJS export names for ESM import in node:
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "displayName.zh-CN": "区块:跨数据源联合查询",
5
5
  "description": "Create a block that joins and displays data from multiple collections across different datasources in a single unified table.",
6
6
  "description.zh-CN": "创建一个区块,可以跨不同数据源联合查询多个表的数据,并在单一表格中展示。",
7
- "version": "0.1.6",
7
+ "version": "0.1.8",
8
8
  "license": "Apache-2.0",
9
9
  "main": "dist/server/index.js",
10
10
  "files": [
@@ -26,6 +26,7 @@
26
26
  "react-i18next": "^11.15.1"
27
27
  },
28
28
  "peerDependencies": {
29
+ "@nocobase/acl": "2.x",
29
30
  "@nocobase/client": "2.x",
30
31
  "@nocobase/server": "2.x",
31
32
  "@nocobase/data-source-manager": "2.x",
@@ -40,5 +41,15 @@
40
41
  "2.x"
41
42
  ],
42
43
  "editionLevel": 0
44
+ },
45
+ "repository": {
46
+ "type": "git",
47
+ "url": "git+https://github.com/OrgGem/nocobase-beta.git",
48
+ "directory": "packages/plugins/plugin-block-cross-join"
49
+ },
50
+ "gitHead": "1b7304686b3349a591094d4d7c394fb6c95b0475",
51
+ "publishConfig": {
52
+ "access": "public",
53
+ "registry": "https://registry.npmjs.org/"
43
54
  }
44
55
  }
package/server.d.ts CHANGED
@@ -1 +1 @@
1
- export * from './dist/server';
1
+ export * from './dist/server';
package/server.js CHANGED
@@ -1 +1 @@
1
- module.exports = require('./dist/server');
1
+ module.exports = require('./dist/server');
@@ -1,34 +1 @@
1
- /**
2
- * This file is part of the NocoBase (R) project.
3
- * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
- * Authors: NocoBase Team.
5
- *
6
- * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
- * For more information, please refer to: https://www.nocobase.com/agreement.
8
- */
9
-
10
- import React, { useState } from 'react';
11
- import { MergeCellsOutlined } from '@ant-design/icons';
12
- import { SchemaInitializerItem, useSchemaInitializer, useSchemaInitializerItem } from '@nocobase/client';
13
- import { CrossJoinConfigurator } from './CrossJoinConfigurator';
14
- import { createCrossJoinBlockUISchema } from './createBlockUISchema';
15
-
16
- export const CrossJoinBlockInitializer: React.FC = () => {
17
- const { insert } = useSchemaInitializer();
18
- const itemConfig = useSchemaInitializerItem();
19
- const [visible, setVisible] = useState(false);
20
-
21
- return (
22
- <>
23
- <SchemaInitializerItem {...itemConfig} icon={<MergeCellsOutlined />} onClick={() => setVisible(true)} />
24
- <CrossJoinConfigurator
25
- visible={visible}
26
- onCancel={() => setVisible(false)}
27
- onSubmit={(config) => {
28
- insert(createCrossJoinBlockUISchema(config));
29
- setVisible(false);
30
- }}
31
- />
32
- </>
33
- );
34
- };
1
+ // DEPRECATED: Removed in v2 migration. See CrossJoinBlockModel.tsx.
@@ -0,0 +1,219 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import { BlockModel } from '@nocobase/client-v2';
4
+ import { tExpr } from '@nocobase/flow-engine';
5
+ import React from 'react';
6
+ import { Table, Empty, Spin } from 'antd';
7
+ import { CrossJoinConfigurator } from './CrossJoinConfigurator';
8
+
9
+ interface JoinDef {
10
+ dataSource: string;
11
+ collection: string;
12
+ joinType: 'left' | 'inner';
13
+ leftField: string;
14
+ rightField: string;
15
+ }
16
+
17
+ interface ColumnDef {
18
+ source: number;
19
+ field: string;
20
+ alias?: string;
21
+ jsonExpand?: string[];
22
+ }
23
+
24
+ interface CrossJoinConfig {
25
+ primarySource: { dataSource: string; collection: string };
26
+ joins: JoinDef[];
27
+ columns: ColumnDef[];
28
+ }
29
+
30
+ export class CrossJoinBlockModel extends BlockModel {
31
+ private _data: Record<string, unknown>[] = [];
32
+ private _loading = false;
33
+ private _page = 1;
34
+ private _pageSize = 20;
35
+ private _total = 0;
36
+ private _configuratorOpen = false;
37
+
38
+ get config(): CrossJoinConfig | undefined {
39
+ return this.stepParams?.crossJoinSettings?.config as CrossJoinConfig | undefined;
40
+ }
41
+
42
+ private async fetchData() {
43
+ const cfg = this.config;
44
+ if (!cfg?.primarySource?.collection) return;
45
+
46
+ this._loading = true;
47
+ this.rerender();
48
+ try {
49
+ const res = await this.context.apiClient.request({
50
+ url: 'crossJoin:query',
51
+ method: 'post',
52
+ data: {
53
+ config: cfg,
54
+ page: this._page,
55
+ pageSize: this._pageSize,
56
+ },
57
+ });
58
+ const body = res?.data;
59
+ this._data = body?.data || [];
60
+ this._total = body?.meta?.count || 0;
61
+ } catch (err) {
62
+ console.error('CrossJoin query failed:', err);
63
+ this._data = [];
64
+ } finally {
65
+ this._loading = false;
66
+ this.rerender();
67
+ }
68
+ }
69
+
70
+ protected onMount() {
71
+ super.onMount();
72
+ this.fetchData();
73
+ }
74
+
75
+ openConfigurator() {
76
+ this._configuratorOpen = true;
77
+ this.rerender();
78
+ }
79
+
80
+ closeConfigurator() {
81
+ this._configuratorOpen = false;
82
+ this.rerender();
83
+ }
84
+
85
+ handleConfigSubmit(config: CrossJoinConfig) {
86
+ this._configuratorOpen = false;
87
+ this.setStepParams('crossJoinSettings', { config });
88
+ this._page = 1;
89
+ this.fetchData();
90
+ }
91
+
92
+ private buildColumns() {
93
+ const cfg = this.config;
94
+ if (cfg?.columns?.length) {
95
+ const cols: {
96
+ title: string;
97
+ dataIndex: string;
98
+ key: string;
99
+ ellipsis: boolean;
100
+ render: (val: unknown) => string;
101
+ }[] = [];
102
+ for (const col of cfg.columns) {
103
+ if (col.jsonExpand?.length) {
104
+ for (const jsonKey of col.jsonExpand) {
105
+ const alias = col.alias ? `${col.alias}.${jsonKey}` : `${col.field}.${jsonKey}`;
106
+ cols.push({
107
+ title: alias,
108
+ dataIndex: alias,
109
+ key: alias,
110
+ ellipsis: true,
111
+ render: (val: unknown) => (val != null ? String(val) : '-'),
112
+ });
113
+ }
114
+ } else {
115
+ const key = col.alias || col.field;
116
+ cols.push({
117
+ title: key,
118
+ dataIndex: key,
119
+ key,
120
+ ellipsis: true,
121
+ render: (val: unknown) => {
122
+ if (val == null) return '-';
123
+ if (typeof val === 'object') return JSON.stringify(val);
124
+ return String(val);
125
+ },
126
+ });
127
+ }
128
+ }
129
+ return cols;
130
+ }
131
+
132
+ if (this._data.length > 0) {
133
+ const firstRow = this._data[0];
134
+ return Object.keys(firstRow).map((key) => ({
135
+ title: key,
136
+ dataIndex: key,
137
+ key,
138
+ ellipsis: true,
139
+ render: (_val: unknown, record: Record<string, unknown>) => {
140
+ const val = record[key];
141
+ if (val == null) return '-';
142
+ if (typeof val === 'object') return JSON.stringify(val);
143
+ return String(val);
144
+ },
145
+ }));
146
+ }
147
+
148
+ return [];
149
+ }
150
+
151
+ // Only override renderComponent — base BlockModel.render() wraps this in BlockItemCard
152
+ // with title, description, heightMode, and settings toolbar automatically.
153
+ renderComponent() {
154
+ const columns = this.buildColumns();
155
+
156
+ return (
157
+ <>
158
+ {this._loading ? (
159
+ <div style={{ textAlign: 'center', padding: 40 }}>
160
+ <Spin />
161
+ </div>
162
+ ) : !this._data.length ? (
163
+ <Empty description="No data" />
164
+ ) : (
165
+ <Table
166
+ dataSource={this._data}
167
+ columns={columns}
168
+ rowKey={(_, index) => String(index)}
169
+ size="middle"
170
+ scroll={{ x: 'max-content' }}
171
+ pagination={{
172
+ current: this._page,
173
+ pageSize: this._pageSize,
174
+ total: this._total,
175
+ showSizeChanger: true,
176
+ showTotal: (total) => `Total ${total} rows`,
177
+ onChange: (page, pageSize) => {
178
+ this._page = page;
179
+ this._pageSize = pageSize;
180
+ this.fetchData();
181
+ },
182
+ }}
183
+ />
184
+ )}
185
+ <CrossJoinConfigurator
186
+ visible={this._configuratorOpen}
187
+ onCancel={() => this.closeConfigurator()}
188
+ onSubmit={(config) => this.handleConfigSubmit(config)}
189
+ initialConfig={this.config}
190
+ />
191
+ </>
192
+ );
193
+ }
194
+ }
195
+
196
+ CrossJoinBlockModel.define({
197
+ label: tExpr('Cross Join'),
198
+ createModelOptions: {
199
+ use: 'CrossJoinBlockModel',
200
+ },
201
+ });
202
+
203
+ // Only register the custom edit-mapping step.
204
+ // Title, description, block height, linkage rules, and remove are all inherited
205
+ // from BlockModel.registerFlow('cardSettings') automatically.
206
+ CrossJoinBlockModel.registerFlow({
207
+ key: 'crossJoinSettings',
208
+ title: tExpr('Cross Join settings'),
209
+ sort: -100,
210
+ steps: {
211
+ editMapping: {
212
+ title: tExpr('Edit mapping'),
213
+ useRawParams: true,
214
+ handler(ctx) {
215
+ (ctx.model as CrossJoinBlockModel).openConfigurator();
216
+ },
217
+ },
218
+ },
219
+ });
@@ -1,88 +1 @@
1
- /**
2
- * This file is part of the NocoBase (R) project.
3
- * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
- * Authors: NocoBase Team.
5
- *
6
- * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
- * For more information, please refer to: https://www.nocobase.com/agreement.
8
- */
9
-
10
- import React, { createContext, useContext, useEffect, useState, useCallback, useMemo } from 'react';
11
- import { useFieldSchema } from '@formily/react';
12
- import { useAPIClient } from '@nocobase/client';
13
-
14
- interface CrossJoinContextValue {
15
- data: Record<string, any>[];
16
- loading: boolean;
17
- pagination: { page: number; pageSize: number; total: number };
18
- config: any;
19
- refresh: () => void;
20
- setPage: (page: number) => void;
21
- setPageSize: (size: number) => void;
22
- }
23
-
24
- const CrossJoinContext = createContext<CrossJoinContextValue | null>(null);
25
-
26
- export const useCrossJoinContext = () => {
27
- return useContext(CrossJoinContext);
28
- };
29
-
30
- export const CrossJoinBlockProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
31
- const fieldSchema = useFieldSchema();
32
- const api = useAPIClient();
33
- const decoratorProps = fieldSchema?.['x-decorator-props'] || {};
34
- const rawConfig = decoratorProps.config;
35
- // eslint-disable-next-line react-hooks/exhaustive-deps
36
- const config = useMemo(() => rawConfig, [JSON.stringify(rawConfig)]);
37
-
38
- const [data, setData] = useState<Record<string, any>[]>([]);
39
- const [loading, setLoading] = useState(false);
40
- const [page, setPage] = useState(1);
41
- const [pageSize, setPageSize] = useState(decoratorProps.params?.pageSize || 20);
42
- const [total, setTotal] = useState(0);
43
-
44
- const fetchData = useCallback(async () => {
45
- if (!config?.primarySource?.collection) return;
46
-
47
- setLoading(true);
48
- try {
49
- const res = await api.request({
50
- url: 'crossJoin:query',
51
- method: 'post',
52
- data: {
53
- config,
54
- page,
55
- pageSize,
56
- },
57
- });
58
- const body = res?.data;
59
- setData(body?.data || []);
60
- setTotal(body?.meta?.count || 0);
61
- } catch (err) {
62
- console.error('CrossJoin query failed:', err);
63
- setData([]);
64
- } finally {
65
- setLoading(false);
66
- }
67
- }, [api, config, page, pageSize]);
68
-
69
- useEffect(() => {
70
- fetchData();
71
- }, [fetchData]);
72
-
73
- return (
74
- <CrossJoinContext.Provider
75
- value={{
76
- data,
77
- loading,
78
- pagination: { page, pageSize, total },
79
- config,
80
- refresh: fetchData,
81
- setPage,
82
- setPageSize,
83
- }}
84
- >
85
- {children}
86
- </CrossJoinContext.Provider>
87
- );
88
- };
1
+ // DEPRECATED: Removed in v2 migration. See CrossJoinBlockModel.tsx.