-
Notifications
You must be signed in to change notification settings - Fork 5.4k
/
workflow.ts
163 lines (129 loc) · 4.81 KB
/
workflow.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
import { flags } from '@oclif/command';
import { ApplicationError, jsonParse } from 'n8n-workflow';
import fs from 'fs';
import glob from 'fast-glob';
import { Container } from 'typedi';
import { WorkflowEntity } from '@db/entities/WorkflowEntity';
import { disableAutoGeneratedIds } from '@db/utils/commandHelpers';
import type { IWorkflowToImport } from '@/Interfaces';
import { BaseCommand } from '../BaseCommand';
import { generateNanoId } from '@db/utils/generators';
import { RoleService } from '@/services/role.service';
import { UM_FIX_INSTRUCTION } from '@/constants';
import { UserRepository } from '@db/repositories/user.repository';
import { ImportService } from '@/services/import.service';
import { WorkflowRepository } from '@/databases/repositories/workflow.repository';
function assertHasWorkflowsToImport(workflows: unknown): asserts workflows is IWorkflowToImport[] {
if (!Array.isArray(workflows)) {
throw new ApplicationError(
'File does not seem to contain workflows. Make sure the workflows are contained in an array.',
);
}
for (const workflow of workflows) {
if (
typeof workflow !== 'object' ||
!Object.prototype.hasOwnProperty.call(workflow, 'nodes') ||
!Object.prototype.hasOwnProperty.call(workflow, 'connections')
) {
throw new ApplicationError('File does not seem to contain valid workflows.');
}
}
}
export class ImportWorkflowsCommand extends BaseCommand {
static description = 'Import workflows';
static examples = [
'$ n8n import:workflow --input=file.json',
'$ n8n import:workflow --separate --input=backups/latest/',
'$ n8n import:workflow --input=file.json --userId=1d64c3d2-85fe-4a83-a649-e446b07b3aae',
'$ n8n import:workflow --separate --input=backups/latest/ --userId=1d64c3d2-85fe-4a83-a649-e446b07b3aae',
];
static flags = {
help: flags.help({ char: 'h' }),
input: flags.string({
char: 'i',
description: 'Input file name or directory if --separate is used',
}),
separate: flags.boolean({
description: 'Imports *.json files from directory provided by --input',
}),
userId: flags.string({
description: 'The ID of the user to assign the imported workflows to',
}),
};
async init() {
disableAutoGeneratedIds(WorkflowEntity);
await super.init();
}
async run(): Promise<void> {
// eslint-disable-next-line @typescript-eslint/no-shadow
const { flags } = this.parse(ImportWorkflowsCommand);
if (!flags.input) {
this.logger.info('An input file or directory with --input must be provided');
return;
}
if (flags.separate) {
if (fs.existsSync(flags.input)) {
if (!fs.lstatSync(flags.input).isDirectory()) {
this.logger.info('The argument to --input must be a directory');
return;
}
}
}
const user = flags.userId ? await this.getAssignee(flags.userId) : await this.getOwner();
let totalImported = 0;
if (flags.separate) {
let { input: inputPath } = flags;
if (process.platform === 'win32') {
inputPath = inputPath.replace(/\\/g, '/');
}
const files = await glob('*.json', {
cwd: inputPath,
absolute: true,
});
totalImported = files.length;
this.logger.info(`Importing ${totalImported} workflows...`);
for (const file of files) {
const workflow = jsonParse<IWorkflowToImport>(fs.readFileSync(file, { encoding: 'utf8' }));
if (!workflow.id) {
workflow.id = generateNanoId();
}
const _workflow = Container.get(WorkflowRepository).create(workflow);
await Container.get(ImportService).importWorkflows([_workflow], user.id);
}
this.reportSuccess(totalImported);
process.exit();
}
const workflows = jsonParse<IWorkflowToImport[]>(
fs.readFileSync(flags.input, { encoding: 'utf8' }),
);
const _workflows = workflows.map((w) => Container.get(WorkflowRepository).create(w));
assertHasWorkflowsToImport(workflows);
totalImported = workflows.length;
await Container.get(ImportService).importWorkflows(_workflows, user.id);
this.reportSuccess(totalImported);
}
async catch(error: Error) {
this.logger.error('An error occurred while importing workflows. See log messages for details.');
this.logger.error(error.message);
}
private reportSuccess(total: number) {
this.logger.info(`Successfully imported ${total} ${total === 1 ? 'workflow.' : 'workflows.'}`);
}
private async getOwner() {
const ownerGlobalRole = await Container.get(RoleService).findGlobalOwnerRole();
const owner =
ownerGlobalRole &&
(await Container.get(UserRepository).findOneBy({ globalRoleId: ownerGlobalRole?.id }));
if (!owner) {
throw new ApplicationError(`Failed to find owner. ${UM_FIX_INSTRUCTION}`);
}
return owner;
}
private async getAssignee(userId: string) {
const user = await Container.get(UserRepository).findOneBy({ id: userId });
if (!user) {
throw new ApplicationError('Failed to find user', { extra: { userId } });
}
return user;
}
}