Last active
May 11, 2021 12:35
-
-
Save maulanasatyaadi/0a451f39f010b889d129d9fe3ab0e446 to your computer and use it in GitHub Desktop.
Revision
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
import dotenv from 'dotenv' | |
import express, { json, urlencoded } from 'express' | |
import process from 'process' | |
import mysql from 'mysql2' | |
import csv from 'csv-parser' | |
import multer from 'multer' | |
import fs from 'fs' | |
import path from 'path' | |
dotenv.config() | |
const PORT = process.env.PORT || 3000 | |
const MYSQL_HOST = process.env.MYSQL_HOST || 'localhost' | |
const MYSQL_PORT = Number(process.env.MYSQL_PORT || '3306') | |
const MYSQL_USER = process.env.MYSQL_USER || 'root' | |
const MYSQL_PASSWORD = process.env.MYSQL_PASSWORD || '' | |
const MYSQL_DATABASE = process.env.MYSQL_DATABASE || 'test' | |
const mysqlConnection = mysql.createConnection({ | |
host: MYSQL_HOST, | |
user: MYSQL_USER, | |
port: MYSQL_PORT, | |
password: MYSQL_PASSWORD, | |
database: MYSQL_DATABASE | |
}) | |
const server = express() | |
const upload = multer({ | |
dest: path.join(__dirname, '../tmp') | |
}) | |
server.use(json()) | |
server.use(urlencoded({extended: true})) | |
server.post('/', upload.single('file'), (req, res) => { | |
const csvFile = req.file | |
const output = [] | |
fs.createReadStream(csvFile.path) | |
.pipe(csv()) | |
.on('data', data => output.push(data)) | |
.on('end', () => { | |
fs.unlinkSync(csvFile.path) | |
const lines = [] | |
output.map(data => lines.push(`(${data.id}, '${data.msisdn}', ${data.max_tagging}, ${data.is_whitelist}, ${data.is_blacklist})`)) | |
mysqlConnection.execute('REPLACE INTO whitelist_tagging (id, msisdn, max_tagging, is_whitelist, is_blacklist) VALUES ' + lines.join(', '), (err) => { | |
if (err !== null) { | |
res.json({ | |
success: false, | |
message: 'Failed to insert data', | |
error: err | |
}) | |
return | |
} | |
res.json({ | |
success: true, | |
message: 'Success insert data', | |
error: null | |
}) | |
}) | |
}) | |
}) | |
server.get('/', (req, res) => { | |
res.json({ | |
success: true, | |
message: { | |
timestamp: Date.now() | |
}, | |
error: null | |
}) | |
}) | |
server.listen(PORT, () => { | |
console.log(`Server has started at port ${PORT}`) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment