Added osmAddress api route

Related to #19
This commit is contained in:
Dmitriy Shishkov 2023-07-15 11:08:15 +03:00
parent 2ce0e5b65d
commit cb848739e5
Signed by: dm1sh
GPG Key ID: 027994B0AA357688
5 changed files with 65 additions and 37 deletions

View File

@ -0,0 +1,12 @@
import { LatLng } from 'leaflet'
import { OsmAddressResponse } from './types'
const initialOsmAddress = ''
const composeOsmAddressURL = (addressPosition: LatLng) =>
`${location.protocol}//nominatim.openstreetmap.org/reverse?format=json&accept-language=ru&lat=${addressPosition.lat}&lon=${addressPosition.lng}`
const processOsmAddress = (data: OsmAddressResponse): string =>
data.display_name
export { initialOsmAddress, composeOsmAddressURL, processOsmAddress }

View File

@ -0,0 +1,17 @@
import { isObject } from '../../utils/types'
type OsmAddressResponse = {
display_name: string
}
const isOsmAddressResponse = (obj: unknown): obj is OsmAddressResponse => isObject(obj, {
'display_name': 'string',
})
export type {
OsmAddressResponse,
}
export {
isOsmAddressResponse,
}

View File

@ -3,3 +3,4 @@ export { default as useBook } from './useBook'
export { default as useAuth } from './useAuth'
export { default as useTrashboxes } from './useTrashboxes'
export { default as useAddAnnouncement } from './useAddAnnouncement'
export { default as useOsmAddresses } from './useOsmAddress'

View File

@ -0,0 +1,17 @@
import { LatLng } from 'leaflet'
import useFetch from './useFetch'
import { composeOsmAddressURL, processOsmAddress } from '../../api/osmAddress'
import { isOsmAddressResponse } from '../../api/osmAddress/types'
const useOsmAddresses = (addressPosition: LatLng) =>
useFetch(
composeOsmAddressURL(addressPosition),
'GET',
false,
isOsmAddressResponse,
processOsmAddress,
''
)
export default useOsmAddresses

View File

@ -5,23 +5,25 @@ import { latLng } from 'leaflet'
import { ClickHandler, LocationMarker, TrashboxMarkers } from '../components'
import { useAddAnnouncement, useTrashboxes } from '../hooks/api'
import { isObject } from '../utils/types'
import { handleHTTPErrors } from '../utils'
import { categories, categoryNames } from '../assets/category'
import { stations, lines, lineNames } from '../assets/metro'
import { gotError } from '../hooks/api/useFetch'
import { fallbackError, gotError } from '../hooks/api/useFetch'
import { useOsmAddresses } from '../hooks/api'
function AddPage() {
const [addressPosition, setAddressPosition] = useState(latLng(59.972, 30.3227))
const [address, setAddress] = useState('')
const trashboxes = useTrashboxes(addressPosition)
const [selectedTrashbox, setSelectedTrashbox] = useState({ index: -1, category: '' })
const address = useOsmAddresses(addressPosition)
useEffect(() => {
if (!gotError(address))
void (async () => {
try {
const res = await fetch(location.protocol + '//nominatim.openstreetmap.org/search?format=json&q=' + address)
const res = await fetch(location.protocol + '//nominatim.openstreetmap.org/search?format=json&q=' + encodeURIComponent(address.data))
handleHTTPErrors(res)
@ -35,27 +37,6 @@ function AddPage() {
})()
}, [address])
useEffect(() => {
void (async () => {
try {
const res = await fetch(`${location.protocol}//nominatim.openstreetmap.org/reverse?format=json&accept-language=ru&lat=${addressPosition.lat}&lon=${addressPosition.lng}`)
handleHTTPErrors(res)
const fetchData: unknown = await res.json()
if (!isObject<{ display_name: string }>(fetchData, { 'display_name': 'string' })) {
throw new Error('Malformed server response')
}
setAddress(fetchData.display_name)
} catch (err) {
console.error(err)
}
})()
}, [addressPosition])
const { doAdd, status } = useAddAnnouncement()
const handleSubmit: FormEventHandler<HTMLFormElement> = (event) => {
@ -66,7 +47,7 @@ function AddPage() {
formData.append('latitude', addressPosition.lat.toString())
formData.append('longtitude', addressPosition.lng.toString())
formData.append('address', address)
formData.append('address', address.data || '') // if address.error
formData.set('bestBy', new Date((formData.get('bestBy') as number | null) || 0).getTime().toString())
void doAdd(formData)
@ -112,7 +93,7 @@ function AddPage() {
url='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
/>
<LocationMarker
address={address}
address={fallbackError(address)}
position={addressPosition}
setPosition={setAddressPosition}
/>
@ -121,7 +102,7 @@ function AddPage() {
/>
</MapContainer>
</div>
<p>Адрес: {address}</p>
<p>Адрес: {fallbackError(address)}</p>
</Form.Group>
<Form.Group className='mb-3' controlId='description'>