MySQL.js 1.91 KB
const mysql = require("mysql");
const fs = require("fs");
const parseICal = require("./ICal");

function jcalToSQL(jcal, userID) {
  const fsql = fs.readFileSync("server/libs/sql.pvdata", "utf8");
  const [id, pw] = fsql.split("\r\n");
  const connection = mysql.createConnection({
    host: "localhost",
    user: id,
    password: pw,
    database: "db",
  });

  connection.connect();

  const commonCols = [
    "userID",
    "uid",
    "label",
    "subjectID",
    "type",
    "description",
    "url",
    "detail",
  ];
  const dateScheCols = [...commonCols, "date"];
  const timeScheCols = [...commonCols, "date", "startTime", "endTime"];
  const dateQueryString =
    "INSERT IGNORE INTO schedules_date (" +
    dateScheCols.join(",") +
    ") VALUES ?";
  const timeQueryString =
    "INSERT IGNORE INTO schedules_time (" +
    timeScheCols.join(",") +
    ") VALUES ?";

  const dateSchedules = [];
  const timeSchedules = [];
  for (const sche of jcal) {
    sche.userID = userID;
    sche.type = "assignment";
    if (sche.scheType === "date")
      dateSchedules.push(dateScheCols.map((col) => sche[col]));
    else if (sche.scheType === "time")
      timeSchedules.push(timeScheCols.map((col) => sche[col]));
    else console.log("unexpected scheType", sche);
  }

  connection.query(dateQueryString, [dateSchedules], (error, result) => {
    if (error) console.log(error);
    else console.log(`schedules_date | ${result.affectedRows} rows added`);
  });
  connection.query(timeQueryString, [timeSchedules], (error, result) => {
    if (error) console.log(error);
    else console.log(`schedules_time | ${result.affectedRows} rows added`);
  });

  connection.end();
}

// iCal의 소유주를 DB에 등록 후 userID get
// subjectID가 subjects, userID가 users에 있어야함
const fdata = fs.readFileSync("C:/Users/teddy/Downloads/data.ics", "utf8");
const jcal = parseICal(fdata);
jcalToSQL(jcal, 1);

module.exports = jcalToSQL;