Suppose I have user entries in my PureScript code with the following type:
{ id :: Number , username :: String , email :: Maybe String , isActive :: Boolean }
CommonJS module derived from PureScript code. Exported user-related functions will be called from external JavaScript code.
In JavaScript code, a βuserβ can be represented as:
var alice = {id: 123, username: 'alice', email: ' alice@example.com ', isActive: true};
email can be null :
var alice = {id: 123, username: 'alice', email: null, isActive: true};
email may be omitted:
var alice = {id: 123, username: 'alice', isActive: true};
isActive may be omitted, in which case true assumed:
var alice = {id: 123, username: 'alice'};
id , unfortunately, is sometimes a numeric string:
var alice = {id: '123', username: 'alice'};
The five JavaScript representations above are equivalent and must contain equivalent PureScript entries.
How do I write a function that takes a JavaScript object and returns a user record? . It would use the default value for the optional null / omitted field, force the id string to a number, and throw if the required field is missing or if the value is of the wrong type.
Two approaches that I see are using FFI in a PureScript module or defining a transform function in external JavaScript code. The latter seems hairy:
function convert(user) { var rec = {}; if (user.email == null) { rec.email = PS.Data_Maybe.Nothing.value; } else if (typeof user.email == 'string') { rec.email = PS.Data_Maybe.Just.create(user.email); } else { throw new TypeError('"email" must be a string or null'); }
I'm not sure how the FFI version will work. I have not worked with effects yet.
I'm sorry this question is not very clear. I still do not have enough understanding to know exactly what exactly I want to know.