Impex module
The impex module load json files into the database and permits asyncronous functions to be inserted as part of the process to gather related information.
Usage
Create a data file in JSON format and execute the impex
service:
base.impex
.import(helpers.insertProduct, 'migrations/dataProductsAppliances.json')
.then(() => {
resolve();
})
.catch(error => reject(error));
dataProductsAppliances.json:
[
{
"sku": "001004721744979",
"title": "Frigidaire - 18.1 Cu. Ft.",
"prices": [ { "amount": 749, "currency": "USD" } ]
},
{
"sku": "001004721740886",
"title": "Whirlpool - 19.3 Cu. Ft.",
"prices": [ { "amount": 799, "currency": "USD" } ]
}
]
If you need to make a request to another service to gather some information (an id by example), create a function that returns a Promise and change the value of the desired property, and add that function to the impex service execution:
const helpers = {
categoryIdByTitle: function (obj, property, title, parent) {
return this.services.call({
name: 'catalog:category.list',
headers: this.impex.defaultHeaders,
circuitbreaker: { timeout: this.impex.defaultTimeout }
}, { title })
.then((result) => {
if (result.ok === false || (result.data && result.data.length === 0)) {
throw new Error(`Category not found '${title}'`);
}
this.impex.setProperty(obj, property, result.data[0].id, parent);
});
}
}
base.impex
.addHelpers(helpers)
.import(helpers.insertProduct, 'migrations/dataProductsAppliances.json')
.then(() => {
resolve();
})
.catch(error => reject(error));
dataProductsAppliances.json
The categoryIdByTitle()
function must be used insted of the value of the property:
[
{
"sku": "001004721744979",
"title": "Frigidaire - 18.1 Cu. Ft.",
"prices": [ { "amount": 749, "currency": "USD" } ],
"categories": [
"Appliances",
"categoryIdByTitle(Top-Freezer)"
]
},
{
"sku": "001004721740886",
"title": "Whirlpool - 19.3 Cu. Ft.",
"prices": [ { "amount": 799, "currency": "USD" } ],
"categories": [
"Appliances",
"categoryIdByTitle(Top-Freezer)"
]
}
]