UNPKG

@flatfile/plugin-autocast

Version:

A plugin for automatically casting values in Flatfile.

9 lines (7 loc) 1.79 kB
import { FlatfileClient } from '@flatfile/api'; import { bulkRecordHook } from '@flatfile/plugin-record-hook'; import { logInfo } from '@flatfile/util-common'; var b=new FlatfileClient;function I(e,t,r){return i=>{i.use(bulkRecordHook(e,async(c,l)=>{let u=l.context.sheetId,s=await b.sheets.get(u);if(!s){logInfo("@flatfile/plugin-autocast","Failed to fetch sheet");return}let p=s.data.config.fields.filter(o=>t?t.includes(o.key):o.type!=="string");c.forEach(o=>{p.forEach(n=>{let a=o.get(n.key),f=T[n.type];if(a&&f&&typeof a!==n.type)try{o.computeIfPresent(n.key,f);}catch(m){o.addError(n.key,m.message||"Failed to cast value");}});});},r));}}var T={string:V,number:h,boolean:N,date:w};function V(e){if(typeof e=="string")return e;if(typeof e=="number")return e.toString();if(typeof e=="boolean")return e?"true":"false";throw new Error(`Failed to cast '${e}' to 'string'`)}function h(e){if(typeof e=="number")return e;if(typeof e=="string"){let t=e.replace(/,/g,"");if(!isNaN(Number(t))){let r=Number(t);if(isFinite(r))return r}}throw new Error("Invalid number")}var R=["1","yes","true","on","t","y",1],F=["-1","0","no","false","off","f","n",0,-1];function N(e){if(typeof e=="boolean")return e;if(typeof e=="string"||typeof e=="number"){if(e==="")return null;let t=typeof e=="string"?e.toLowerCase():e;if(R.includes(t))return !0;if(F.includes(t))return !1}throw new Error("Invalid boolean")}function w(e){let t=Number(e),r=isNaN(t)?e:t;if(typeof r=="string"||typeof r=="number"){let i=new Date(r);if(!isNaN(i.getTime()))return i.toUTCString()}throw new Error("Invalid date")} export { F as FALSY_VALUES, R as TRUTHY_VALUES, I as autocast, N as castBoolean, w as castDate, h as castNumber, V as castString }; //# sourceMappingURL=index.browser.js.map //# sourceMappingURL=index.browser.js.map