118 lines
2.9 KiB
JavaScript
118 lines
2.9 KiB
JavaScript
const db = require('../db/models');
|
|
const Weather_dataDBApi = require('../db/api/weather_data');
|
|
const processFile = require('../middlewares/upload');
|
|
const ValidationError = require('./notifications/errors/validation');
|
|
const csv = require('csv-parser');
|
|
const axios = require('axios');
|
|
const config = require('../config');
|
|
const stream = require('stream');
|
|
|
|
module.exports = class Weather_dataService {
|
|
static async create(data, currentUser) {
|
|
const transaction = await db.sequelize.transaction();
|
|
try {
|
|
await Weather_dataDBApi.create(data, {
|
|
currentUser,
|
|
transaction,
|
|
});
|
|
|
|
await transaction.commit();
|
|
} catch (error) {
|
|
await transaction.rollback();
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
static async bulkImport(req, res, sendInvitationEmails = true, host) {
|
|
const transaction = await db.sequelize.transaction();
|
|
|
|
try {
|
|
await processFile(req, res);
|
|
const bufferStream = new stream.PassThrough();
|
|
const results = [];
|
|
|
|
await bufferStream.end(Buffer.from(req.file.buffer, 'utf-8')); // convert Buffer to Stream
|
|
|
|
await new Promise((resolve, reject) => {
|
|
bufferStream
|
|
.pipe(csv())
|
|
.on('data', (data) => results.push(data))
|
|
.on('end', async () => {
|
|
console.log('CSV results', results);
|
|
resolve();
|
|
})
|
|
.on('error', (error) => reject(error));
|
|
});
|
|
|
|
await Weather_dataDBApi.bulkImport(results, {
|
|
transaction,
|
|
ignoreDuplicates: true,
|
|
validate: true,
|
|
currentUser: req.currentUser,
|
|
});
|
|
|
|
await transaction.commit();
|
|
} catch (error) {
|
|
await transaction.rollback();
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
static async update(data, id, currentUser) {
|
|
const transaction = await db.sequelize.transaction();
|
|
try {
|
|
let weather_data = await Weather_dataDBApi.findBy(
|
|
{ id },
|
|
{ transaction },
|
|
);
|
|
|
|
if (!weather_data) {
|
|
throw new ValidationError('weather_dataNotFound');
|
|
}
|
|
|
|
const updatedWeather_data = await Weather_dataDBApi.update(id, data, {
|
|
currentUser,
|
|
transaction,
|
|
});
|
|
|
|
await transaction.commit();
|
|
return updatedWeather_data;
|
|
} catch (error) {
|
|
await transaction.rollback();
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
static async deleteByIds(ids, currentUser) {
|
|
const transaction = await db.sequelize.transaction();
|
|
|
|
try {
|
|
await Weather_dataDBApi.deleteByIds(ids, {
|
|
currentUser,
|
|
transaction,
|
|
});
|
|
|
|
await transaction.commit();
|
|
} catch (error) {
|
|
await transaction.rollback();
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
static async remove(id, currentUser) {
|
|
const transaction = await db.sequelize.transaction();
|
|
|
|
try {
|
|
await Weather_dataDBApi.remove(id, {
|
|
currentUser,
|
|
transaction,
|
|
});
|
|
|
|
await transaction.commit();
|
|
} catch (error) {
|
|
await transaction.rollback();
|
|
throw error;
|
|
}
|
|
}
|
|
};
|