import { Strapi } from "@strapi/strapi"; import { Client } from "@googlemaps/google-maps-services-js"; const zipcode2coordinates = async (zipcode) => { const client = new Client({}); const resp = await client.geocode({ params: { address: zipcode, key: process.env.GOOGLE_MAPS_API_KEY || "", }, }); if (resp.data.results.length > 0) { return resp.data.results[0].geometry.location; } else { throw new Error(`Zipcode not found with zipcode ${zipcode}`); } }; const addressToLatAndLng = async (address) => { const client = new Client({}); const resp = await client.geocode({ params: { address: address, key: process.env.GOOGLE_MAPS_API_KEY || "", }, }); if (resp.data.results.length > 0) { return resp.data.results[0].geometry.location; } else { throw new Error(`Lat and Lng not found with address ${address}`); } }; export default ({ strapi }: { strapi: Strapi }) => { const apiName = "plugin::dutchie-plus.zipcode"; const exportServices = { graphqlFindOne: async (args) => { const { zipcode } = args; if (!(zipcode && zipcode.length === 5)) { throw new Error(`Invalid zip code ${zipcode}`); } let [entity] = await strapi.entityService.findMany(apiName, { filters: { zipcode }, limit: 1, }); if (!entity) { const location = await zipcode2coordinates(zipcode); const { lat, lng } = location; entity = await strapi.entityService.create(apiName, { data: { zipcode: zipcode, latitude: lat, longitude: lng, }, }); } return { value: entity, info: { args, resourceUID: apiName, }, }; }, }; return exportServices; };