-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmapped-loader.ts
More file actions
74 lines (58 loc) · 2.6 KB
/
mapped-loader.ts
File metadata and controls
74 lines (58 loc) · 2.6 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
69
70
71
72
73
74
/**
* Example: MappedSheetsLoader — type-safe column renaming
*
* Extends MappedSheetsLoader (which wraps MappedServiceBase from
* @kylebrodeur/type-safe-mapping) to automatically rename sheet column
* headers to your internal model fields in a single typed call.
*
* Run (after building the package):
* SA_EMAIL=<email> SA_KEY=<key> SHEET_ID=<id> npx ts-node examples/mapped-loader.ts
*/
import { SheetsLoader, MappedSheetsLoader } from '../src/index.js';
import type { MappingDefinition } from '@kylebrodeur/type-safe-mapping';
// ── 1. Declare the shape that matches your sheet's column headers exactly ──────
type ProductSheetRow = {
'Product ID': string;
'Product Name': string;
'Unit Price': string;
'In Stock': string;
[key: string]: string; // required: mapping values must also be keyof TSource
};
// ── 2. Define the column → model field mapping ─────────────────────────────────
const productMapping = {
'Product ID': 'id',
'Product Name': 'name',
'Unit Price': 'unitPrice',
'In Stock': 'inStock',
} as const satisfies MappingDefinition<ProductSheetRow>;
// ── 3. Extend MappedSheetsLoader and implement fieldMapping ────────────────────
class ProductSheetLoader extends MappedSheetsLoader<ProductSheetRow, typeof productMapping> {
protected fieldMapping = productMapping;
}
// ── 4. Use it ──────────────────────────────────────────────────────────────────
async function main() {
const sheetId = process.env.SHEET_ID;
if (!sheetId) throw new Error('SHEET_ID environment variable is required');
const sheetsLoader = new SheetsLoader({
auth: {
credentials: {
client_email: process.env.SA_EMAIL!,
private_key: process.env.SA_KEY!.replace(/\\n/g, '\n'),
},
},
});
const loader = new ProductSheetLoader(sheetsLoader);
// products is fully typed: { id: string; name: string; unitPrice: string; inStock: string }[]
const products = await loader.loadMapped(sheetId, 'Products!A1:D500');
console.log(`Loaded ${products.length} products`);
console.log('First product:', products[0]);
// Post-process: coerce types after renaming
const parsed = products.map((p) => ({
id: p.id,
name: p.name,
unitPrice: parseFloat(p.unitPrice) || 0,
inStock: p.inStock?.toLowerCase() === 'true',
}));
console.log('Parsed first product:', parsed[0]);
}
main().catch(console.error);