@nocobase/plugin-user-data-sync 1.4.0-alpha.20240826214041

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.
Files changed (45) hide show
  1. package/LICENSE.txt +121 -0
  2. package/README.md +1 -0
  3. package/client.d.ts +2 -0
  4. package/client.js +1 -0
  5. package/dist/client/Options.d.ts +12 -0
  6. package/dist/client/UserDataSyncSource.d.ts +10 -0
  7. package/dist/client/index.d.ts +21 -0
  8. package/dist/client/index.js +10 -0
  9. package/dist/client/locale/index.d.ts +10 -0
  10. package/dist/client/schemas/user-data-sync-sources.d.ts +155 -0
  11. package/dist/client/sourceType.d.ts +24 -0
  12. package/dist/externalVersion.js +24 -0
  13. package/dist/index.d.ts +10 -0
  14. package/dist/index.js +56 -0
  15. package/dist/locale/en-US.json +19 -0
  16. package/dist/locale/zh-CN.json +22 -0
  17. package/dist/server/actions/user-data.d.ts +16 -0
  18. package/dist/server/actions/user-data.js +64 -0
  19. package/dist/server/collections/user-data-sync-records-resources.d.ts +10 -0
  20. package/dist/server/collections/user-data-sync-records-resources.js +54 -0
  21. package/dist/server/collections/user-data-sync-records.d.ts +10 -0
  22. package/dist/server/collections/user-data-sync-records.js +85 -0
  23. package/dist/server/collections/user-data-sync-sources.d.ts +10 -0
  24. package/dist/server/collections/user-data-sync-sources.js +109 -0
  25. package/dist/server/collections/user-data-sync-tasks.d.ts +10 -0
  26. package/dist/server/collections/user-data-sync-tasks.js +131 -0
  27. package/dist/server/index.d.ts +11 -0
  28. package/dist/server/index.js +51 -0
  29. package/dist/server/models/sync-source.d.ts +15 -0
  30. package/dist/server/models/sync-source.js +38 -0
  31. package/dist/server/plugin.d.ts +27 -0
  32. package/dist/server/plugin.js +100 -0
  33. package/dist/server/sync-source-manager.d.ts +28 -0
  34. package/dist/server/sync-source-manager.js +71 -0
  35. package/dist/server/sync-source.d.ts +42 -0
  36. package/dist/server/sync-source.js +107 -0
  37. package/dist/server/user-data-resource-manager.d.ts +103 -0
  38. package/dist/server/user-data-resource-manager.js +214 -0
  39. package/dist/server/user-data-sync-service.d.ts +23 -0
  40. package/dist/server/user-data-sync-service.js +125 -0
  41. package/dist/swagger/index.d.ts +116 -0
  42. package/dist/swagger/index.js +138 -0
  43. package/package.json +18 -0
  44. package/server.d.ts +2 -0
  45. package/server.js +1 -0
@@ -0,0 +1,28 @@
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
+ import { Registry } from '@nocobase/utils';
10
+ import { SyncSource, SyncSourceExtend } from './sync-source';
11
+ import { Context } from '@nocobase/actions';
12
+ import { SyncSourceModel } from './models/sync-source';
13
+ type SyncSourceConfig = {
14
+ syncSource: SyncSourceExtend<SyncSource>;
15
+ title?: string;
16
+ };
17
+ export declare class SyncSourceManager {
18
+ protected syncSourceTypes: Registry<SyncSourceConfig>;
19
+ registerType(syncSourceType: string, syncSourceConfig: SyncSourceConfig): void;
20
+ listTypes(): {
21
+ name: string;
22
+ title: string;
23
+ }[];
24
+ getByName(name: string, ctx: Context): Promise<SyncSource>;
25
+ getById(id: number, ctx: Context): Promise<SyncSource>;
26
+ create(sourceInstance: SyncSourceModel, ctx: Context): SyncSource;
27
+ }
28
+ export {};
@@ -0,0 +1,71 @@
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
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var sync_source_manager_exports = {};
28
+ __export(sync_source_manager_exports, {
29
+ SyncSourceManager: () => SyncSourceManager
30
+ });
31
+ module.exports = __toCommonJS(sync_source_manager_exports);
32
+ var import_utils = require("@nocobase/utils");
33
+ class SyncSourceManager {
34
+ syncSourceTypes = new import_utils.Registry();
35
+ registerType(syncSourceType, syncSourceConfig) {
36
+ this.syncSourceTypes.register(syncSourceType, syncSourceConfig);
37
+ }
38
+ listTypes() {
39
+ return Array.from(this.syncSourceTypes.getEntities()).map(([syncSourceType, source]) => ({
40
+ name: syncSourceType,
41
+ title: source.title
42
+ }));
43
+ }
44
+ async getByName(name, ctx) {
45
+ const repo = ctx.db.getRepository("userDataSyncSources");
46
+ const sourceInstance = await repo.findOne({ filter: { enabled: true, name } });
47
+ if (!sourceInstance) {
48
+ throw new Error(`SyncSource [${name}] is not found.`);
49
+ }
50
+ return this.create(sourceInstance, ctx);
51
+ }
52
+ async getById(id, ctx) {
53
+ const repo = ctx.db.getRepository("userDataSyncSources");
54
+ const sourceInstance = await repo.findOne({ filter: { enabled: true }, filterByTk: id });
55
+ if (!sourceInstance) {
56
+ throw new Error(`SyncSource [${id}] is not found.`);
57
+ }
58
+ return this.create(sourceInstance, ctx);
59
+ }
60
+ create(sourceInstance, ctx) {
61
+ const { syncSource } = this.syncSourceTypes.get(sourceInstance.sourceType) || {};
62
+ if (!syncSource) {
63
+ throw new Error(`SyncSourceType [${sourceInstance.sourceType}] is not found.`);
64
+ }
65
+ return new syncSource({ sourceInstance, options: sourceInstance.options, ctx });
66
+ }
67
+ }
68
+ // Annotate the CommonJS export names for ESM import in node:
69
+ 0 && (module.exports = {
70
+ SyncSourceManager
71
+ });
@@ -0,0 +1,42 @@
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
+ import { Context } from '@nocobase/actions';
10
+ import { SyncSourceModel } from './models/sync-source';
11
+ import { UserData } from './user-data-resource-manager';
12
+ export type SyncSourceConfig = {
13
+ sourceInstance: SyncSourceModel;
14
+ options: {
15
+ [key: string]: any;
16
+ };
17
+ ctx: Context;
18
+ };
19
+ interface ISyncSource {
20
+ pull(): Promise<UserData[]>;
21
+ }
22
+ export declare abstract class SyncSource implements ISyncSource {
23
+ instance: SyncSourceModel;
24
+ protected options: {
25
+ [key: string]: any;
26
+ };
27
+ protected ctx: Context;
28
+ constructor(config: SyncSourceConfig);
29
+ abstract pull(): Promise<UserData[]>;
30
+ newTask(): Promise<any>;
31
+ beginTask(taskId: number): Promise<void>;
32
+ endTask(params: EndTaskParams): Promise<void>;
33
+ retryTask(taskId: number): Promise<any>;
34
+ }
35
+ export type SyncSourceExtend<T extends SyncSource> = new (config: SyncSourceConfig) => T;
36
+ type EndTaskParams = {
37
+ taskId: number;
38
+ success: boolean;
39
+ cost?: number;
40
+ message?: string;
41
+ };
42
+ export {};
@@ -0,0 +1,107 @@
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
+ var __create = Object.create;
11
+ var __defProp = Object.defineProperty;
12
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
13
+ var __getOwnPropNames = Object.getOwnPropertyNames;
14
+ var __getProtoOf = Object.getPrototypeOf;
15
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
16
+ var __export = (target, all) => {
17
+ for (var name in all)
18
+ __defProp(target, name, { get: all[name], enumerable: true });
19
+ };
20
+ var __copyProps = (to, from, except, desc) => {
21
+ if (from && typeof from === "object" || typeof from === "function") {
22
+ for (let key of __getOwnPropNames(from))
23
+ if (!__hasOwnProp.call(to, key) && key !== except)
24
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
25
+ }
26
+ return to;
27
+ };
28
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
29
+ // If the importer is in node compatibility mode or this is not an ESM
30
+ // file that has been converted to a CommonJS file using a Babel-
31
+ // compatible transform (i.e. "__esModule" has not been set), then set
32
+ // "default" to the CommonJS "module.exports" for node compatibility.
33
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
34
+ mod
35
+ ));
36
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
37
+ var sync_source_exports = {};
38
+ __export(sync_source_exports, {
39
+ SyncSource: () => SyncSource
40
+ });
41
+ module.exports = __toCommonJS(sync_source_exports);
42
+ var import_dayjs = __toESM(require("dayjs"));
43
+ class SyncSource {
44
+ instance;
45
+ options;
46
+ ctx;
47
+ constructor(config) {
48
+ const { options, ctx, sourceInstance } = config;
49
+ this.instance = sourceInstance;
50
+ this.options = options;
51
+ this.ctx = ctx;
52
+ }
53
+ async newTask() {
54
+ const batch = generateUniqueNumber();
55
+ return await this.instance.createTask({ batch, status: "init" });
56
+ }
57
+ async beginTask(taskId) {
58
+ const tasks = await this.instance.getTasks({ where: { id: taskId } });
59
+ if (!tasks && !tasks.length) {
60
+ throw new Error(`Task [${taskId}] is not found.`);
61
+ }
62
+ const task = tasks[0];
63
+ if (task.status !== "init") {
64
+ throw new Error(`Task [${taskId}] is not init.`);
65
+ }
66
+ task.status = "processing";
67
+ await task.save();
68
+ }
69
+ async endTask(params) {
70
+ const { taskId, success, cost, message } = params;
71
+ const tasks = await this.instance.getTasks({ where: { id: taskId } });
72
+ if (!tasks && !tasks.length) {
73
+ throw new Error(`Task [${taskId}] is not found.`);
74
+ }
75
+ const task = tasks[0];
76
+ if (task.status !== "processing") {
77
+ throw new Error(`Task [${taskId}] is not processing.`);
78
+ }
79
+ task.status = success ? "success" : "failed";
80
+ task.cost = cost;
81
+ task.message = message;
82
+ await task.save();
83
+ }
84
+ async retryTask(taskId) {
85
+ const tasks = await this.instance.getTasks({ where: { id: taskId } });
86
+ if (!tasks && !tasks.length) {
87
+ throw new Error(`Task [${taskId}] is not found.`);
88
+ }
89
+ const task = tasks[0];
90
+ if (task.status !== "failed") {
91
+ throw new Error(`Task [${taskId}] is not failed.`);
92
+ }
93
+ task.status = "processing";
94
+ task.message = "";
95
+ await task.save();
96
+ return task;
97
+ }
98
+ }
99
+ function generateUniqueNumber() {
100
+ const formattedDate = (0, import_dayjs.default)().format("YYYYMMDDHHmmss");
101
+ const randomDigits = Math.floor(1e5 + Math.random() * 9e5);
102
+ return formattedDate + randomDigits;
103
+ }
104
+ // Annotate the CommonJS export names for ESM import in node:
105
+ 0 && (module.exports = {
106
+ SyncSource
107
+ });
@@ -0,0 +1,103 @@
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
+ import { Toposort, ToposortOptions } from '@nocobase/utils';
10
+ import Database, { Repository } from '@nocobase/database';
11
+ import { SystemLogger } from '@nocobase/logger';
12
+ export type FormatUser = {
13
+ uid: string;
14
+ username?: string;
15
+ email?: string;
16
+ nickname?: string;
17
+ phone?: string;
18
+ departments?: string[];
19
+ isDeleted?: boolean;
20
+ [key: string]: any;
21
+ };
22
+ export type FormatDepartment = {
23
+ uid: string;
24
+ title?: string;
25
+ parentUid?: string;
26
+ isDeleted?: boolean;
27
+ [key: string]: any;
28
+ };
29
+ export type UserDataRecord = FormatUser | FormatDepartment;
30
+ export type SyncDataType = 'user' | 'department';
31
+ export type SyncAccept = SyncDataType;
32
+ export type OriginRecord = {
33
+ id: number;
34
+ sourceName: string;
35
+ sourceUk: string;
36
+ dataType: SyncDataType;
37
+ metaData: UserDataRecord;
38
+ resources: {
39
+ resource: string;
40
+ resourcePk: string;
41
+ }[];
42
+ };
43
+ export type UserData = {
44
+ dataType: SyncDataType;
45
+ matchKey?: string;
46
+ records: UserDataRecord[];
47
+ sourceName: string;
48
+ };
49
+ export type PrimaryKey = number | string;
50
+ export type RecordResourceChanged = {
51
+ resourcesPk: PrimaryKey;
52
+ isDeleted: boolean;
53
+ };
54
+ export declare abstract class UserDataResource {
55
+ name: string;
56
+ accepts: SyncAccept[];
57
+ db: Database;
58
+ logger: SystemLogger;
59
+ constructor(db: Database, logger: SystemLogger);
60
+ abstract update(record: OriginRecord, resourcePks: PrimaryKey[], matchKey?: string): Promise<RecordResourceChanged[]>;
61
+ abstract create(record: OriginRecord, matchKey: string): Promise<RecordResourceChanged[]>;
62
+ get syncRecordRepo(): Repository<any, any>;
63
+ get syncRecordResourceRepo(): Repository<any, any>;
64
+ }
65
+ export type SyncResult = {
66
+ resource: string;
67
+ detail: {
68
+ count: {
69
+ all: number;
70
+ success: number;
71
+ failed: number;
72
+ };
73
+ failedRecords: {
74
+ record: UserDataRecord;
75
+ message: string;
76
+ }[];
77
+ };
78
+ };
79
+ export declare class UserDataResourceManager {
80
+ resources: Toposort<UserDataResource>;
81
+ syncRecordRepo: Repository;
82
+ syncRecordResourceRepo: Repository;
83
+ logger: SystemLogger;
84
+ registerResource(resource: UserDataResource, options?: ToposortOptions): void;
85
+ set db(value: Database);
86
+ saveOriginRecords(data: UserData): Promise<void>;
87
+ findOriginRecords({ sourceName, dataType, sourceUks }: {
88
+ sourceName: any;
89
+ dataType: any;
90
+ sourceUks: any;
91
+ }): Promise<OriginRecord[]>;
92
+ addResourceToOriginRecord({ recordId, resource, resourcePk }: {
93
+ recordId: any;
94
+ resource: any;
95
+ resourcePk: any;
96
+ }): Promise<void>;
97
+ removeResourceFromOriginRecord({ recordId, resource, resourcePk }: {
98
+ recordId: any;
99
+ resource: any;
100
+ resourcePk: any;
101
+ }): Promise<void>;
102
+ updateOrCreate(data: UserData): Promise<SyncResult[]>;
103
+ }
@@ -0,0 +1,214 @@
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
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var user_data_resource_manager_exports = {};
28
+ __export(user_data_resource_manager_exports, {
29
+ UserDataResource: () => UserDataResource,
30
+ UserDataResourceManager: () => UserDataResourceManager
31
+ });
32
+ module.exports = __toCommonJS(user_data_resource_manager_exports);
33
+ var import_utils = require("@nocobase/utils");
34
+ class UserDataResource {
35
+ name;
36
+ accepts;
37
+ db;
38
+ logger;
39
+ constructor(db, logger) {
40
+ this.db = db;
41
+ this.logger = logger;
42
+ }
43
+ get syncRecordRepo() {
44
+ return this.db.getRepository("userDataSyncRecords");
45
+ }
46
+ get syncRecordResourceRepo() {
47
+ return this.db.getRepository("userDataSyncRecordsResources");
48
+ }
49
+ }
50
+ class UserDataResourceManager {
51
+ resources = new import_utils.Toposort();
52
+ syncRecordRepo;
53
+ syncRecordResourceRepo;
54
+ logger;
55
+ registerResource(resource, options) {
56
+ if (!resource.name) {
57
+ throw new Error('"name" for user data synchronize resource is required');
58
+ }
59
+ if (!resource.accepts) {
60
+ throw new Error('"accepts" for user data synchronize resource is required');
61
+ }
62
+ this.resources.add(resource, { tag: resource.name, ...options });
63
+ }
64
+ set db(value) {
65
+ this.syncRecordRepo = value.getRepository("userDataSyncRecords");
66
+ this.syncRecordResourceRepo = value.getRepository("userDataSyncRecordsResources");
67
+ }
68
+ async saveOriginRecords(data) {
69
+ for (const record of data.records) {
70
+ if (record.uid === void 0) {
71
+ throw new Error(`record must has uid, error record: ${JSON.stringify(record)}`);
72
+ }
73
+ const syncRecord = await this.syncRecordRepo.findOne({
74
+ where: {
75
+ sourceName: data.sourceName,
76
+ sourceUk: record.uid,
77
+ dataType: data.dataType
78
+ }
79
+ });
80
+ if (syncRecord) {
81
+ syncRecord.lastMetaData = syncRecord.metaData;
82
+ syncRecord.metaData = record;
83
+ await syncRecord.save();
84
+ } else {
85
+ await this.syncRecordRepo.create({
86
+ values: {
87
+ sourceName: data.sourceName,
88
+ sourceUk: record.uid,
89
+ dataType: data.dataType,
90
+ metaData: record
91
+ }
92
+ });
93
+ }
94
+ }
95
+ }
96
+ async findOriginRecords({ sourceName, dataType, sourceUks }) {
97
+ return await this.syncRecordRepo.find({
98
+ appends: ["resources"],
99
+ filter: { sourceName, dataType, sourceUk: { $in: sourceUks } }
100
+ });
101
+ }
102
+ async addResourceToOriginRecord({ recordId, resource, resourcePk }) {
103
+ const syncRecord = await this.syncRecordRepo.findOne({
104
+ filter: {
105
+ id: recordId
106
+ }
107
+ });
108
+ if (syncRecord) {
109
+ await syncRecord.createResource({
110
+ resource,
111
+ resourcePk
112
+ });
113
+ }
114
+ }
115
+ async removeResourceFromOriginRecord({ recordId, resource, resourcePk }) {
116
+ const recordResource = await this.syncRecordResourceRepo.findOne({
117
+ where: {
118
+ recordId,
119
+ resource,
120
+ resourcePk
121
+ }
122
+ });
123
+ if (recordResource) {
124
+ await recordResource.destroy();
125
+ }
126
+ }
127
+ async updateOrCreate(data) {
128
+ var _a, _b, _c, _d, _e;
129
+ await this.saveOriginRecords(data);
130
+ const { dataType, sourceName, records, matchKey } = data;
131
+ const sourceUks = records.map((record) => record.uid);
132
+ let processed = false;
133
+ const syncResults = [];
134
+ for (const resource of this.resources.nodes) {
135
+ if (!resource.accepts.includes(dataType)) {
136
+ continue;
137
+ }
138
+ const associateResource = resource.name;
139
+ processed = true;
140
+ const originRecords = await this.findOriginRecords({ sourceName, sourceUks, dataType });
141
+ if (!(originRecords && originRecords.length)) {
142
+ continue;
143
+ }
144
+ const successRecords = [];
145
+ const failedRecords = [];
146
+ for (const originRecord of originRecords) {
147
+ const resourceRecords = (_a = originRecord.resources) == null ? void 0 : _a.filter(
148
+ (r) => r.resource === associateResource
149
+ );
150
+ let recordResourceChangeds;
151
+ if (resourceRecords && resourceRecords.length > 0) {
152
+ const resourcePks = resourceRecords.map((r) => r.resourcePk);
153
+ try {
154
+ recordResourceChangeds = await resource.update(originRecord, resourcePks, matchKey);
155
+ (_b = this.logger) == null ? void 0 : _b.debug(`update record success. Data changed: ${JSON.stringify(recordResourceChangeds)}`);
156
+ successRecords.push(originRecord.metaData);
157
+ } catch (error) {
158
+ (_c = this.logger) == null ? void 0 : _c.warn(`update record error: ${error.message}`, { originRecord });
159
+ failedRecords.push({ record: originRecord.metaData, message: error.message });
160
+ continue;
161
+ }
162
+ } else {
163
+ try {
164
+ recordResourceChangeds = await resource.create(originRecord, matchKey);
165
+ (_d = this.logger) == null ? void 0 : _d.debug(`create record success. Data changed: ${JSON.stringify(recordResourceChangeds)}`);
166
+ successRecords.push(originRecord.metaData);
167
+ } catch (error) {
168
+ (_e = this.logger) == null ? void 0 : _e.warn(`create record error: ${error.message}`, { originRecord });
169
+ failedRecords.push({ record: originRecord.metaData, message: error.message });
170
+ continue;
171
+ }
172
+ }
173
+ if (!recordResourceChangeds || recordResourceChangeds.length === 0) {
174
+ continue;
175
+ }
176
+ for (const { resourcesPk, isDeleted } of recordResourceChangeds) {
177
+ if (isDeleted) {
178
+ await this.removeResourceFromOriginRecord({
179
+ recordId: originRecord.id,
180
+ resource: associateResource,
181
+ resourcePk: resourcesPk
182
+ });
183
+ } else {
184
+ await this.addResourceToOriginRecord({
185
+ recordId: originRecord.id,
186
+ resource: associateResource,
187
+ resourcePk: resourcesPk
188
+ });
189
+ }
190
+ }
191
+ }
192
+ syncResults.push({
193
+ resource: associateResource,
194
+ detail: {
195
+ count: {
196
+ all: originRecords.length,
197
+ success: successRecords.length,
198
+ failed: failedRecords.length
199
+ },
200
+ failedRecords
201
+ }
202
+ });
203
+ }
204
+ if (!processed) {
205
+ throw new Error(`dataType "${dataType}" is not support`);
206
+ }
207
+ return syncResults;
208
+ }
209
+ }
210
+ // Annotate the CommonJS export names for ESM import in node:
211
+ 0 && (module.exports = {
212
+ UserDataResource,
213
+ UserDataResourceManager
214
+ });
@@ -0,0 +1,23 @@
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
+ import { SyncResult, UserDataResourceManager } from './user-data-resource-manager';
10
+ import { SyncSourceManager } from './sync-source-manager';
11
+ import { Context } from '@nocobase/actions';
12
+ import { SyncSource } from './sync-source';
13
+ import { Logger } from '@nocobase/logger';
14
+ export declare class UserDataSyncService {
15
+ resourceManager: UserDataResourceManager;
16
+ sourceManager: SyncSourceManager;
17
+ logger: Logger;
18
+ constructor(resourceManager: UserDataResourceManager, sourceManager: SyncSourceManager, logger: Logger);
19
+ pull(sourceName: string, ctx: Context): Promise<void>;
20
+ push(data: any): Promise<SyncResult[]>;
21
+ retry(sourceId: number, taskId: number, ctx: Context): Promise<void>;
22
+ runSync(source: SyncSource, task: any, ctx: Context): Promise<void>;
23
+ }