firestoreに登録されたデータをCSV出力する処理を、cloud functionsで作成しています。
json2csvを利用してほぼうまく出力できているのですが一点だけ問題があります。
データの登録日付をfirestoreのtimestamp型で保存しているのですが出力した際に、
csv
1{"_seconds":1552796058,"_nanoseconds":32000000}
という用に出力されてしまいます。
js
1import * as functions from 'firebase-functions' 2import * as admin from 'firebase-admin'; 3admin.initializeApp(); 4import * as iconv from 'iconv-lite'; 5import * as json2csv from 'json2csv'; 6 7 8exports.list = functions 9 .https 10 .onRequest((request, response) => { 11 const j2c = json2csv.parse; 12 const db = admin.firestore(); 13 const ordersRef = db.collection('user'); 14 return ordersRef.get() 15 .then((querySnapshot) => { 16 const orders: DocumentData[] = []; 17 querySnapshot.forEach(doc => { 18 const order = doc.data(); 19 orders.push(order); 20 }); 21 const fields = { // 出力項目定義 22 fields: [ 23 { label: '会員番号', value: 'shopCustomerNo',stringify: true }, 24 { label: '登録日時', value: 'insDt'}, // 日付変換できない 25 { label: '姓', value: 'username1',stringify: true }, 26 { label: '名', value: 'username2',stringify: true }, 27 }; 28 29 ; // ヘッダー項目名定義 30 const csv = j2c(orders, fields); 31 const csvShiftJis = iconv.encode(csv, "Shift_JIS") 32 response.setHeader( 33 "Content-disposition", 34 "attachment; filename=user.csv" 35 ); 36 response.set("Content-Type", "text/csv; charset=Shift_JIS"); 37 response.status(200).send(csvShiftJis); 38 return "" 39 }).catch((err) => { 40 response.status(200).send("エラー発生: " + err); 41 return Promise.resolve(); 42 }); 43 });
上記のinsDTをfield指定する際に、toDate()できればいいのかと思うのですが、
公式のサンプルを見てもうまくいきません。
js
1{ 2 fields: [ 3 // Supports label -> simple path 4 { 5 label: 'some label', // (optional, column will be labeled 'path.to.something' if not defined) 6 value: 'path.to.something', // data.path.to.something 7 default: 'NULL' // default if value is not found (optional, overrides `defaultValue` for column) 8 }, 9 10 // Supports label -> derived value 11 { 12 label: 'some label', // Supports duplicate labels (required, else your column will be labeled [function]) 13 value: (row, field) => row.path1 + row.path2, // field = { label, default } 14 default: 'NULL', // default if value function returns null or undefined 15 stringify: true // If value is function use this flag to signal if resulting string will be quoted (stringified) or not (optional, default: true) 16 }, 17 18 // Support pathname -> pathvalue 19 'simplepath', // equivalent to {value:'simplepath'} 20 'path.to.value' // also equivalent to {value:'path.to.value'} 21 ] 22}
何かいい方法をご存知の方はいませんでしょうか?
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。