Last active
July 7, 2018 08:48
-
-
Save SeyZ/6792cc3f51895d91f0e05cc0f1545094 to your computer and use it in GitHub Desktop.
doc-lumber-how-to-import-data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* /forest/products.js */ | |
const Liana = require('forest-express-sequelize'); | |
const models = require('../models'); | |
Liana.collection('products', { | |
actions: [{ | |
name: 'Import data', | |
endpoint: '/forest/products/actions/import-data', | |
type: 'global', | |
fields: [{ | |
field: 'CSV file', | |
description: 'A semicolon separated values file stores tabular data (numbers and text) in plain text', | |
type: 'File', | |
isRequired: true | |
}, { | |
field: 'Type', | |
description: 'Specify the product type to import', | |
type: 'Enum', | |
enums: ['phone', 'dress', 'toy'], | |
isRequired: true | |
}] | |
}], | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* /routes/products.js */ | |
const P = require('bluebird'); | |
const express = require('express'); | |
const router = express.Router(); | |
const Liana = require('forest-express-sequelize'); | |
const faker = require('faker'); | |
const parseDataUri = require('parse-data-uri'); | |
const csv = require('csv'); | |
const models = require('../models'); | |
router.post('/products/actions/import-data', Liana.ensureAuthenticated, | |
(req, res) => { | |
let parsed = parseDataUri(req.body.data.attributes.values['CSV file']); | |
let productType = req.body.data.attributes.values['Type']; | |
csv.parse(parsed.data, { delimiter: ';' }, function (err, rows) { | |
if (err) { | |
res.status(400).send({ | |
error: `Cannot import data: ${err.message}` }); | |
} else { | |
return P | |
.each(rows, (row) => { | |
// Random price for the example purpose. In a real situation, the price | |
// should certainly be available in the CSV file. | |
let price = faker.commerce.price(5, 1000) * 100; | |
return models.products.create({ | |
label: row[0], | |
price: price, | |
picture: row[1] | |
}); | |
}) | |
.then(() => { | |
res.send({ success: 'Data successfuly imported!' }); | |
}); | |
} | |
}); | |
}); | |
module.exports = router; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment