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 (!!event.address) {
13 const query = encodeURI(event.address);
14 try {
15 const { data } = await axios.get(
16 ` https://nominatim.openstreetmap.org/search?format=json&q=${query}`
17 );
18 if (Array.isArray(data) && data.length > 0) {
19 const [entity] = data;
20 event.position = [entity.lat, entity.lon];
21 } else
22 strapi.log.info(
23 `No location from Nominatim API for ${event.address}`
24 );
25 } catch (error) {
26 strapi.log.error(error);
27 }
28 }
29 },
30 async beforeUpdate(params, event) {
31 if (!!event.address) {
32 const query = encodeURI(event.address);
33 try {
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 event.position = [entity.lat, entity.lon];
40 } else
41 strapi.log.info(
42 `No location from Nominatim API for ${event.address}`
43 );
44 } catch (error) {
45 strapi.log.error(error);
46 }
47 }
48 },
49 },
50};