add product model and seed script
This commit is contained in:
@@ -4,6 +4,7 @@ const http = require('http');
|
||||
const minimist = require('minimist');
|
||||
const { host, port } = require('../server/config');
|
||||
const fetchCustomers = require('./lib/fetch_customers');
|
||||
const fetchProducts = require('./lib/fetch_products');
|
||||
|
||||
const argv = minimist(process.argv.slice(2));
|
||||
const modelName = argv._[0];
|
||||
@@ -18,6 +19,30 @@ function testConnection(conn) {
|
||||
});
|
||||
}
|
||||
|
||||
function writeRecords(records, opts = {}) {
|
||||
const options = Object.assign({
|
||||
host,
|
||||
port,
|
||||
path: '/api/customers',
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
}, opts);
|
||||
|
||||
return Promise.all(records.map(record => new Promise((resolve, reject) => {
|
||||
const req = http.request(options, (res) => {
|
||||
res.setEncoding('utf8');
|
||||
res.on('data', () => {});
|
||||
res.on('end', resolve);
|
||||
});
|
||||
|
||||
req.on('error', reject);
|
||||
req.write(JSON.stringify(record));
|
||||
req.end();
|
||||
})));
|
||||
}
|
||||
|
||||
function populateDatabase(model) {
|
||||
console.log('Populating model:', model);
|
||||
let task = false;
|
||||
@@ -25,35 +50,20 @@ function populateDatabase(model) {
|
||||
switch (model.toLowerCase()) {
|
||||
case 'customers':
|
||||
task = fetchCustomers(37)
|
||||
.then((customers) => {
|
||||
const tasks = customers.map((customer) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const options = {
|
||||
host,
|
||||
port,
|
||||
path: '/api/customers',
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
};
|
||||
|
||||
const req = http.request(options, (res) => {
|
||||
res.setEncoding('utf8');
|
||||
res.on('data', () => {});
|
||||
res.on('end', resolve);
|
||||
});
|
||||
|
||||
req.on('error', reject)
|
||||
req.write(JSON.stringify(customer));
|
||||
req.end();
|
||||
});
|
||||
});
|
||||
|
||||
return Promise.all(tasks);
|
||||
})
|
||||
.then(customers => writeRecords(customers, {
|
||||
path: '/api/customers',
|
||||
}))
|
||||
.then(results => console.log('Customer(s) added', results.length));
|
||||
break;
|
||||
|
||||
case 'products':
|
||||
task = fetchProducts(25)
|
||||
.then(customers => writeRecords(customers, {
|
||||
path: '/api/products',
|
||||
}))
|
||||
.then(results => console.log('Product(s) added', results.length));
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new Error(`Model not found or supported: ${model}`);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user