api/event/models/event.js (view raw)
1'use strict';
2const axios = require('axios');
3const moment = require('moment');
4require('moment/locale/fr-ch');
5/**
6 * Read the documentation (https://strapi.io/documentation/v3.x/concepts/models.html#lifecycle-hooks)
7 * to customize this model
8 */
9
10module.exports = {
11 lifecycles: {
12 async beforeCreate(event) {
13 // If user provides an address, get its lat/lng position using OSM API
14 if (event.address) {
15 const query = encodeURI(event.address);
16 try {
17 const {data} = await axios.get(
18 ` https://nominatim.openstreetmap.org/search?format=json&q=${query}`
19 );
20 if (Array.isArray(data) && data.length > 0) {
21 const [entity] = data;
22 event.position = [entity.lat, entity.lon];
23 } else
24 strapi.log.info(
25 `No location from Nominatim API for ${event.address}`
26 );
27 } catch (error) {
28 strapi.log.error(error);
29 }
30 }
31
32 // If user accepts newsletters, subscribe it
33 if (event.newsletter)
34 strapi.plugins['sendgrid'].services.contacts.subscribe(event.email);
35 },
36 async beforeUpdate(params, event) {
37 if (event.address) {
38 const query = encodeURI(event.address);
39 try {
40 const {data} = await axios.get(
41 ` https://nominatim.openstreetmap.org/search?format=json&q=${query}`
42 );
43 if (Array.isArray(data) && data.length > 0) {
44 const [entity] = data;
45 event.position = [entity.lat, entity.lon];
46 } else
47 strapi.log.info(
48 `No location from Nominatim API for ${event.address}`
49 );
50 } catch (error) {
51 strapi.log.error(error);
52 }
53 }
54 },
55
56 async afterCreate(event) {
57 let eventTime = '';
58 if (event.date) {
59 eventTime = ', ' + moment(eventTime.date).format('dddd Do MMMM YYYY');
60 }
61 let eventAddress = '';
62 if (event.address) {
63 eventAddress = ', ' + event.address;
64 }
65 const {STRAPI_URL = ''} = process.env;
66
67 try {
68 await strapi.plugins['sendgrid'].services.email.send({
69 to: event.email,
70 from: 'caroster@octree.ch',
71 templateId: 'd-a1b5043fb186411ea4b57ea956625093',
72 dynamic_template_data: {
73 eventName: event.name,
74 eventTime,
75 eventAddress,
76 eventLink: `${STRAPI_URL}/e/${event.id}`,
77 },
78 });
79 } catch (error) {
80 strapi.log.error(
81 `Impossible to send email notification to ${event.email} for event#${
82 event.id
83 }. Error: ${JSON.stringify(error)}`
84 );
85 }
86 },
87 },
88};