all repos — caroster @ 445bdba5156505c28a56150a62f080b720e91b8d

[Octree] Group carpool to your event https://caroster.io

backend/api/event/models/event.js (view raw)

 1'use strict';
 2const axios = require('axios');
 3const moment = require('moment');
 4const uuid = require('uuid');
 5const sendgrid = require('../../../lib/sendgrid');
 6require('moment/locale/fr-ch');
 7
 8const {STRAPI_URL = ''} = process.env;
 9
10module.exports = {
11  lifecycles: {
12    async beforeCreate(event) {
13      if (!event.uuid) event.uuid = uuid.v4();
14      // If user provides an address, get its lat/lng position using OSM API
15      if (event.address) event.position = getPosition(event.address);
16      // If user accepts newsletters, subscribe it
17      if (event.newsletter) sendgrid.subscribe(event.email);
18    },
19    async afterCreate(event) {
20      sendEmailToCreator(event);
21    },
22
23    async beforeUpdate(params, event) {
24      const eventInDb = await strapi.services.event.findOne(params);
25      if (eventInDb && !eventInDb.uuid) event.uuid = uuid.v4();
26      if (event.address) event.position = getPosition(event.address);
27    },
28  },
29};
30
31const getPosition = async address => {
32  try {
33    const query = encodeURI(address);
34    const {data} = await axios.get(
35      `https://nominatim.openstreetmap.org/search?format=json&q=${query}`
36    );
37    if (Array.isArray(data) && data.length > 0) {
38      const [entity] = data;
39      return [entity.lat, entity.lon];
40    } else strapi.log.info(`No location from Nominatim API for ${address}`);
41  } catch (error) {
42    strapi.log.error(error);
43  }
44};
45
46const sendEmailToCreator = async event => {
47  try {
48    const templateId = await strapi.plugins[
49      'email-designer'
50    ].services.template.getId('creator_notif');
51    await strapi.plugins['email-designer'].services.email.sendTemplatedEmail(
52      {
53        to: event.email,
54      },
55      {
56        templateId,
57      },
58      {
59        event,
60        eventTime: event.date
61          ? moment(event.date).format('dddd D MMMM YYYY')
62          : null,
63        eventLink: `${STRAPI_URL}/e/${event.uuid}`,
64      }
65    );
66  } catch (error) {
67    console.error(error);
68    strapi.log.error(
69      `Impossible to send email notification to ${event.email} for event#${
70        event.id
71      }. Error: ${JSON.stringify(error)}`
72    );
73  }
74};