Реагировать на большие проблемы с календарем - PullRequest
0 голосов
/ 11 декабря 2018

У меня возникли некоторые проблемы с моим приложением «реактивный большой календарь».Я использую API для получения и дальнейшего отображения некоторых дат, но это не работает правильно.Он показывает одинаковый часовой пояс везде и отображает события за день до ввода.Вот код API

const router = require('express').Router();
const dbSettingsUrl = process.env.DATABASE_URL;
const db = require('../../common/helpers/db')(dbSettingsUrl);
const request = require('request-promise');
const {google} = require('googleapis');

router.post('/user', (req, res, next) => {
  const body = req.body

  if (typeof body.externalUserId === 'undefined' && typeof body.externalUserId !== 'number') {
    return next(new Error('externalUserId ID was not specified.'));
  }

  if (typeof body.googleToken === 'undefined' && typeof body.googleToken !== 'string') {
    return next(new Error('googleToken ID was not specified.'));
  }

  const sql = `INSERT INTO "user" (external_id_, google_token) VALUES ($1, $2) RETURNING *;`

  db.query(sql, [body.externalUserId, body.googleToken])
    .then((result) => {
      return res.json(result);
    })
    .catch((err) => {
      return next(err)
    })
})

router.get('/users/:id', (req, res, next) => {
  const params = req.params

  if (typeof req.params === 'undefined' && typeof req.params !== 'number') {
    return next(new Error('user ID was not specified.'));
  }

  const sql = `SELECT * FROM "user" WHERE external_id_ = $1 ORDER BY id DESC LIMIT 1;`

  db.query(sql, [params.id])
    .then((result) => {
      return res.json(result);
    })
    .catch((err) => {
      return next(err)
    })
})

router.get('/user/get-events', (req, res, next) => {
  const query = req.query;
  const date  = new Date();

  if (typeof req.query === 'undefined') {
    return next(new Error('query was not specified.'));
  }

  const sql = 'SELECT * FROM "user" WHERE external_id_ = $1 ORDER BY id DESC LIMIT 1;';
  return db.oneOrNone(sql, [query.userId])
    .then(user => {
      const calendar = google.calendar('v3');
      const oauth2Client = new google.auth.OAuth2({
        client_id: process.env.GOOGLE_API_CLIENT_ID,
        client_secret: process.env.GOOGLE_API_SECRET
      });
      oauth2Client.setCredentials(JSON.parse(user.google_token));
      calendar.events.list({
        auth: oauth2Client,
        calendarId: 'primary',
        timeMin: new Date(date.getFullYear(), date.getMonth() - 1, 1),
      }, function(err, result) {
        if (err) {
          console.log('There was an error contacting the Calendar service: ' + err);
          return next(err);
        }
        return res.json(result.data);
      });

    })
    .catch((err) => {
      return next(err)
    });
})

router.post('/user/add-event', (req, res, next) => {
  const body = req.body
  const requestURL = `${process.env.EXTERNAL_API_URL}/appointments/upsertSchedule`;

  if (typeof body.userId === 'undefined' && typeof body.userId !== 'number') {
    return next(new Error('userId ID was not specified.'));
  }

  const options = {
    url: requestURL,
    headers: req.headers,
    method: 'POST',
    body: body,
    json: true,
    gzip: true,
    rejectUnauthorized: false,
  }

  //TODO: fix this
  let tmpGlobal = null;

  request(options)
    .then((result) => {
      tmpGlobal = result;
      return result
    })
    .then((result) => {
      const sql = 'SELECT * FROM "user" WHERE external_id_ = $1 ORDER BY id DESC LIMIT 1;';
      return db.oneOrNone(sql, [body.userId]);
    })
    .then((user) => {
      const calendar = google.calendar('v3');
      const oauth2Client = new google.auth.OAuth2({
        client_id: process.env.GOOGLE_API_CLIENT_ID,
        client_secret: process.env.GOOGLE_API_SECRET
      });
      oauth2Client.setCredentials(JSON.parse(user.google_token));

      const event = {
        'summary': 'StudyKIK Appointment',
        'location': body.siteAddress,
        'description': 'Appointment description',
        'start': {
          'dateTime': body.time,
          'timeZone': body.timezone,
        },
        'end': {
          'dateTime': body.time,
          'timeZone': body.timezone,
        }
      };

      calendar.events.insert({
        auth: oauth2Client,
        calendarId: 'primary',
        resource: event,
      }, function(err, event) {
        if (err) {
          console.log('There was an error contacting the Calendar service: ' + err);
          return next(err);
        }
        console.log('Event created: %s', event.htmlLink);
        return res.json(tmpGlobal);
      });

    })
    .catch((err) => {
      return next(err)
    })
})



router.post('/user/edit-event', (req, res, next) => {
  const body = req.body

  if (typeof body.userId === 'undefined' && typeof body.userId !== 'number') {
    return next(new Error('userId ID was not specified.'));
  }

  if (typeof body.id === 'undefined' && typeof body.id !== 'number') {
    return next(new Error('google event ID was not specified.'));
  }

  const sql = 'SELECT * FROM "user" WHERE external_id_ = $1 ORDER BY id DESC LIMIT 1;';
  return db.oneOrNone(sql, [body.userId])
    .then(user => {
      const calendar = google.calendar('v3');
      const oauth2Client = new google.auth.OAuth2({
        client_id: process.env.GOOGLE_API_CLIENT_ID,
        client_secret: process.env.GOOGLE_API_SECRET
      });
      oauth2Client.setCredentials(JSON.parse(user.google_token));
      let resource = {
        'summary': body.title,
        'description': body.description ? body.description : null,
        'start': {
          'dateTime': body.start,
          'timeZone': body.timezone,
        },
        'end': {
          'dateTime': body.end,
          'timeZone': body.timezone,
        }
      };

      if (body.onlyDate) {
        resource = {
          'summary': body.title,
          'description': body.description ? body.description : null,
          'start': {
            'date': body.start,
          },
          'end': {
            'date': body.end,
          }
        };
      }

      calendar.events.patch({
        auth: oauth2Client,
        calendarId: 'primary',
        eventId: body.id,
        resource,
      }, function(err, event) {
        if (err) {
          console.log('There was an error contacting the Calendar service: ' + err);
          return next(err);
        }
        console.log('Event updated: %s', event.data);
        return res.json(event.data);
      });

    })
    .catch((err) => {
      return next(err)
    });
})

router.post('/user/add-custom-event', (req, res, next) => {
  const body = req.body
  const requestURL = `${process.env.EXTERNAL_API_URL}/appointments/upsertSchedule`;

  if (typeof body.userId === 'undefined' && typeof body.userId !== 'number') {
    return next(new Error('userId ID was not specified.'));
  }

  const sql = 'SELECT * FROM "user" WHERE external_id_ = $1 ORDER BY id DESC LIMIT 1;';
  return db.oneOrNone(sql, [body.userId])
    .then((user) => {
      const calendar = google.calendar('v3');
      const oauth2Client = new google.auth.OAuth2({
        client_id: process.env.GOOGLE_API_CLIENT_ID,
        client_secret: process.env.GOOGLE_API_SECRET
      });
      oauth2Client.setCredentials(JSON.parse(user.google_token));

      const event = {
        'summary': body.title,
        'description': body.description ? body.description : null,
        'start': {
          'dateTime': body.start,
          'timeZone': body.timezone,
        },
        'end': {
          'dateTime': body.end,
          'timeZone': body.timezone,
        }
      };

      calendar.events.insert({
        auth: oauth2Client,
        calendarId: 'primary',
        resource: event,
      }, function(err, event) {
        if (err) {
          console.log('There was an error contacting the Calendar service: ' + err);
          return next(err);
        }
        console.log('Event created: %s', event.data);
        return res.json(event.data);
      });

    })
    .catch((err) => {
      return next(err)
    })
})

module.exports = router;

Может кто-нибудь сказать, все ли в порядке с этим кодом?У меня могут быть проблемы с другими файлами, но я хочу знать об этом сейчас.

...