First you need to correctly start your Promise, since you are not resolving it, I like to do it like so:
const insertIntoTable = function(data) {
return Promise.resolve()
.then(() => {
const entry = {
Id: data.id,
Method: data.Method,
Status: data.PaymentStatus,
InsertedAt: (new Date().getTime())
}
// Do something with entry
})
.catch((error) => {
console.log(error);
});
}
This way you can throw inside you validation (instead of rejecting)
You could create a validation function that checks for undefined, like so:
const validate = property => {
if (property === undefined) throw 'data missing required property'
return property
}
And use it like so:
const entry = {
Id: validate(data.id),
Method: validate(data.Method),
Status: validate(data.PaymentStatus),
InsertedAt: (new Date().getTime())
}
But this way you would always get the same error. You could change it to show an error based on the property name:
const getAndValidate = (data, propertyName) => {
const property = data[propertyName]
if (property === undefined) throw 'data missing the required property' + propertyName
return property
}
And use it like so:
const entry = {
Id: getAndValidate(data, 'id'),
Method: getAndValidate(data, 'Method'),
Status: getAndValidate(data, 'PaymentStatus'),
InsertedAt: (new Date().getTime())
}
This way you get the right error everytime, but I don't like to access the attributes using string names