Skip to content

Commit

Permalink
feat(useVehicleLocations): support operatorRef (#96)
Browse files Browse the repository at this point in the history
  • Loading branch information
NoamGaash authored Oct 21, 2023
1 parent 73110bc commit 7567de5
Showing 1 changed file with 30 additions and 5 deletions.
35 changes: 30 additions & 5 deletions src/api/useVehicleLocations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,20 +39,40 @@ const loadedLocations = new Map<
* it also caches the data, so if the same interval is requested again, it will not load it again.
*/
class LocationObservable {
constructor({ from, to, lineRef }: { from: Dateable; to: Dateable; lineRef?: number }) {
this.#loadData({ from, to, lineRef })
constructor({
from,
to,
lineRef,
operatorRef,
}: {
from: Dateable
to: Dateable
lineRef?: number
operatorRef?: number
}) {
this.#loadData({ from, to, lineRef, operatorRef })
}

data: VehicleLocation[] = []
loading = true

async #loadData({ from, to, lineRef }: { from: Dateable; to: Dateable; lineRef?: number }) {
async #loadData({
from,
to,
lineRef,
operatorRef,
}: {
from: Dateable
to: Dateable
lineRef?: number
operatorRef?: number
}) {
let offset = 0
for (let i = 1; this.loading; i++) {
let url = config.apiUrl
url += `&${config.fromField}=${formatTime(from)}&${config.toField}=${formatTime(to)}&limit=${
config.limit * i
}&offset=${offset}`
}&offset=${offset}&siri_routes__operator_ref=${operatorRef}`
if (lineRef) url += `&${config.lineRefField}=${lineRef}`

const response = await fetchWithQueue(url)
Expand Down Expand Up @@ -109,15 +129,17 @@ function getLocations({
to,
lineRef,
onUpdate,
operatorRef,
}: {
from: Dateable
to: Dateable
lineRef?: number
operatorRef?: number
onUpdate: (locations: VehicleLocation[] | { finished: true }) => void // the observer will be called every time with all the locations that were loaded
}) {
const key = `${formatTime(from)}-${formatTime(to)}`
if (!loadedLocations.has(key)) {
loadedLocations.set(key, new LocationObservable({ from, to, lineRef }))
loadedLocations.set(key, new LocationObservable({ from, to, lineRef, operatorRef }))
}
const observable = loadedLocations.get(key)!
return observable.observe(onUpdate)
Expand All @@ -139,11 +161,13 @@ export default function useVehicleLocations({
from,
to,
lineRef,
operatorRef,
splitMinutes: split = 1,
}: {
from: Dateable
to: Dateable
lineRef?: number
operatorRef?: number
splitMinutes?: false | number
}) {
const [locations, setLocations] = useState<VehicleLocation[]>([])
Expand All @@ -156,6 +180,7 @@ export default function useVehicleLocations({
from,
to,
lineRef,
operatorRef,
onUpdate: (data) => {
if ('finished' in data) {
setIsLoading((prev) => {
Expand Down

0 comments on commit 7567de5

Please sign in to comment.