-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.ts
More file actions
68 lines (61 loc) · 1.87 KB
/
example.ts
File metadata and controls
68 lines (61 loc) · 1.87 KB
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
import { ContinuationRow, CsvImporter, ProductDefinition } from "./src";
const importer = new CsvImporter();
importer.addDefinition(
ProductDefinition.create("simple")
.matchWhen((row) => row.type === "simple")
.requireFields(["handle", "title", "type", "sku"]),
);
importer.addDefinition(
ProductDefinition.create("variable")
.matchWhen((row) => row.type === "variable")
.requireFields([
"handle",
"title",
"type",
"sku",
"option 1 name",
"option 1 value",
])
.allowContinuationRows(
ContinuationRow.create()
.label("variant-row")
.matchWhen((row) => !!row.sku)
.requireFields(["handle", "sku", "option 1 value"])
.forbidFields(["title"]),
),
);
importer.addDefinition(
ProductDefinition.create("serialized")
.matchWhen((row) => row.type === "serialized")
.requireFields(["handle", "title", "type", "sku", "imei"])
.allowContinuationRows(
ContinuationRow.create()
.label("imei-row")
.matchWhen((row) => !!row.imei && !row.sku)
.requireFields(["handle", "imei"])
.forbidFields(["title", "type", "sku", "price", "cost"]),
),
);
import { readFileSync } from "node:fs";
const csv = readFileSync("./import-template.csv", "utf-8");
const result = importer.parse(csv);
if (result.ok) {
console.log(`✓ All ${result.valid.length} product groups are valid.\n`);
for (const group of result.valid) {
console.log(
` [${group.definition}] ${group.handle}` +
(group.continuations.length
? ` (+${group.continuations.length} continuation rows)`
: ""),
);
}
} else {
console.log(`✗ ${result.errors.length} error(s) found:\n`);
for (const err of result.errors) {
const field = err.field ? ` [field: ${err.field}]` : "";
console.log(` Line ${err.line} (${err.handle})${field}: ${err.message}`);
}
if (result.valid.length > 0) {
console.log(`\n ${result.valid.length} group(s) passed validation.`);
}
}