all repos — caroster @ 801844aae058fe032f6b8b9f198489cc6c48c6c3

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

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

 1'use strict';
 2const axios = require('axios');
 3
 4/**
 5 * Read the documentation (https://strapi.io/documentation/v3.x/concepts/models.html#lifecycle-hooks)
 6 * to customize this model
 7 */
 8
 9module.exports = {
10  lifecycles: {
11    async beforeCreate(event) {
12      // If user provides an address, get its lat/lng position using OSM API
13      if (event.address) {
14        const query = encodeURI(event.address);
15        try {
16          const {data} = await axios.get(
17            ` https://nominatim.openstreetmap.org/search?format=json&q=${query}`
18          );
19          if (Array.isArray(data) && data.length > 0) {
20            const [entity] = data;
21            event.position = [entity.lat, entity.lon];
22          } else
23            strapi.log.info(
24              `No location from Nominatim API for ${event.address}`
25            );
26        } catch (error) {
27          strapi.log.error(error);
28        }
29      }
30
31      // If user accepts newsletters, subscribe it
32      if (event.newsletter)
33        strapi.plugins['sendgrid'].services.contacts.subscribe(event.email);
34    },
35    async beforeUpdate(params, event) {
36      if (event.address) {
37        const query = encodeURI(event.address);
38        try {
39          const {data} = await axios.get(
40            ` https://nominatim.openstreetmap.org/search?format=json&q=${query}`
41          );
42          if (Array.isArray(data) && data.length > 0) {
43            const [entity] = data;
44            event.position = [entity.lat, entity.lon];
45          } else
46            strapi.log.info(
47              `No location from Nominatim API for ${event.address}`
48            );
49        } catch (error) {
50          strapi.log.error(error);
51        }
52      }
53    },
54  },
55};