Skip to content

Instantly share code, notes, and snippets.

@remexre
Last active August 18, 2021 00:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save remexre/2c26bcd3aed185b21f99bfbb80b48856 to your computer and use it in GitHub Desktop.
Save remexre/2c26bcd3aed185b21f99bfbb80b48856 to your computer and use it in GitHub Desktop.
#!/usr/bin/env -S deno run --allow-net
const api = async (path: string) => {
const url = `https://svc.metrotransit.org/NexTrip/${path}?format=json`;
const resp = await fetch(url);
if (!resp.ok) {
console.error(`Got back status ${resp.status} ${resp.statusText}`);
Deno.exit(1);
}
return await resp.json();
};
const getRoutes = () => api("Routes");
const getDirections = (route: number) => api(`Directions/${route}`);
const getStops = (route: number, direction: number) =>
api(`Stops/${route}/${direction}`);
const getDepartures = (route: number, direction: number, stop: string) =>
api(`${route}/${direction}/${stop}`);
enum UsageKind {
Routes,
Directions,
Stops
}
const usage = async (kind: UsageKind) => {
console.error("Usage: ./i-like-trains.ts <route> <direction> <stop>");
console.error(" e.g. ./i-like-trains.ts 902 0 <stop>");
switch (kind) {
case UsageKind.Routes:
console.error("Available routes:");
for (const route of await getRoutes())
console.log(` ${route.Route} ${JSON.stringify(route.Description)}`);
break;
case UsageKind.Directions:
console.error("Available directions:");
for (const dir of await getDirections(parseInt(Deno.args[0])))
console.log(` ${dir.Value} ${JSON.stringify(dir.Text)}`);
break;
case UsageKind.Stops:
console.error("Available stop:");
for (const stop of await getStops(parseInt(Deno.args[0]),
parseInt(Deno.args[1])))
console.log(` ${stop.Value} ${JSON.stringify(stop.Text)}`);
break;
}
Deno.exit(-1);
};
const isInt = (x: string) => !isNaN(parseInt(x));
if (Deno.args.length == 0 || Deno.args.length > 3 || !isInt(Deno.args[0])) {
usage(UsageKind.Routes);
} else if (Deno.args.length == 1 || !isInt(Deno.args[1])) {
usage(UsageKind.Directions);
} else if (Deno.args.length == 2 ||
(await getStops(parseInt(Deno.args[0]), parseInt(Deno.args[1])))
.some((x: string) => Deno.args[2] === x)) {
usage(UsageKind.Stops);
} else if (Deno.args.length == 3) {
const departures = await getDepartures(parseInt(Deno.args[0]),
parseInt(Deno.args[1]), Deno.args[2]);
for (const departure of departures)
console.log(departure.DepartureText);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment