Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions backend/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,5 @@ DB_DATABASE=auth_db
DB_HOST=localhost
JWT_SECRET=«generate_strong_secret_here»
JWT_EXPIRES_IN=604800

GOOGLE_API_KEY=
3 changes: 3 additions & 0 deletions backend/config/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,7 @@ module.exports = {
secret: process.env.JWT_SECRET,
expiresIn: process.env.JWT_EXPIRES_IN,
},
apiKeys: {
google: process.env.GOOGLE_API_KEY,
},
};
107 changes: 107 additions & 0 deletions backend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"author": "",
"license": "ISC",
"dependencies": {
"@googlemaps/google-maps-services-js": "^3.3.4",
"bcryptjs": "^2.4.3",
"cookie-parser": "^1.4.6",
"cors": "^2.8.5",
Expand Down
73 changes: 65 additions & 8 deletions backend/routes/api/business.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
const asyncHandler = require("express-async-handler");
const createHttpError = require("http-errors");
const express = require("express");
const { check, query } = require("express-validator");
const { Client } = require("@googlemaps/google-maps-services-js");
const { check, query, validationResult } = require("express-validator");
const { Op } = require("sequelize");

const { Business, Review, User } = require("../../db/models");
const {
apiKeys: { google: googleApiKey },
} = require("../../config");
const {
handleValidationErrors,
sanitizePaginationQuery,
Expand Down Expand Up @@ -83,9 +87,44 @@ router.get(
})
);

const client = new Client();
const addressToLatLong = asyncHandler(async (req) => {
// If the lat and long are passed in the body, skip requesting the information from Google
if (req.body.lat && req.body.long) {
return { lat: req.body.lat, long: req.body.long };
}

const validationErrors = validationResult(req);

if (!validationErrors.isEmpty()) {
return;
}

const { address, city, state, zipCode } = req.body;

const geocodeResult = await client.geocode({
params: {
address: `${address}, ${city}, ${state} ${zipCode}`,
key: googleApiKey,
},
});

if (
!geocodeResult.data ||
geocodeResult.data.status !== "OK" ||
!geocodeResult.data.results ||
geocodeResult.data.results.length < 1
) {
return;
}

return {
lat: geocodeResult.data.results[0].geometry.location.lat,
long: geocodeResult.data.results[0].geometry.location.lng,
};
});

const validateBusiness = [
check("name").trim().exists({ checkFalsy: true }).withMessage("Enter a name"),
check("description").trim().optional({ checkFalsy: true }),
check("address")
.trim()
.exists({ checkFalsy: true })
Expand All @@ -99,6 +138,29 @@ const validateBusiness = [
.trim()
.exists({ checkFalsy: true })
.withMessage("Enter a zip code"),
check("address").custom(async (_, { req }) => {
try {
const latLong = await addressToLatLong(req);

if (!latLong) {
throw new Error("Failed to find this address. Try again.");
}

req.body.lat = latLong.lat;
req.body.long = latLong.long;
return true;
} catch {
throw new Error("Failed to find this address. Try again.");
}
}),

check("name").trim().exists({ checkFalsy: true }).withMessage("Enter a name"),
check("description").trim().optional({ checkFalsy: true }),
check("displayImage")
.trim()
.optional({ checkFalsy: true })
.isURL()
.withMessage("Enter a valid image url"),
check("lat")
.exists({ checkFalsy: true })
.withMessage("Enter a latitude")
Expand All @@ -109,11 +171,6 @@ const validateBusiness = [
.withMessage("Enter a longitude")
.isDecimal()
.withMessage("Enter a valid longitude"),
check("displayImage")
.trim()
.optional({ checkFalsy: true })
.isURL()
.withMessage("Enter a valid image url"),
handleValidationErrors,
];

Expand Down
36 changes: 0 additions & 36 deletions frontend/src/components/business/BusinessEditor.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,6 @@ const BusinessEditor = ({ addNew }) => {
const [city, setCity] = useState(businessData.city || "");
const [state, setState] = useState(businessData.state || "");
const [zipCode, setZipCode] = useState(businessData.zipCode || "");
const [lat, setLat] = useState(businessData.lat || "");
const [long, setLong] = useState(businessData.long || "");
const [displayImage, setDisplayImage] = useState(
businessData.displayImage || ""
);
Expand All @@ -73,8 +71,6 @@ const BusinessEditor = ({ addNew }) => {
city,
state,
zipCode,
lat,
long,
displayImage,
};

Expand Down Expand Up @@ -217,38 +213,6 @@ const BusinessEditor = ({ addNew }) => {
required
/>
</InputWrapper>
<InputWrapper>
<InputField
label="Latitude"
fullWidth
id="business-latitude"
value={lat}
onChange={(e) => setLat(e.target.value)}
inputProps={{
type: "number",
step: "any",
}}
error={!!errors.lat}
helperText={errors.lat}
required
/>
</InputWrapper>
<InputWrapper>
<InputField
label="Longitude"
fullWidth
id="business-longitude"
value={long}
onChange={(e) => setLong(e.target.value)}
inputProps={{
type: "number",
step: "any",
}}
error={!!errors.long}
helperText={errors.long}
required
/>
</InputWrapper>
</form>
<Actions>
<div>
Expand Down