npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

mbta-client

v1.1.10

Published

MBTA API v3 Node.js Client Library

Downloads

64

Readme

MTBA API Client

mbta-client is a promise-based Node.js client library for the MTBA API v3, with a few helper functions to parse response data.

Build Status Coverage Status NPM Version

Installation:

npm i mbta-client

Basic Usage

Fetch functions

import MBTA from 'mbta-client';

// Instantiate MBTA with your API key
const mbta = new MBTA(YOUR_API_KEY);

// Fetch data, passing filters as options. Filter documentation for
// each function: https://api-v3.mbta.com/docs/swagger/index.html#/
const predictions = await mbta.fetchPredictions({ stop: 42 });

// Use an array for filters that accept multiple values
const stops = await mbta.fetchStops({ id: [70080, 'Back Bay'] });

// Some fetch functions accept a `type` or `route_type` filter. This can
// be provided as a string ('bus', 'subway', etc.) or route_type code:
// https://developers.google.com/transit/gtfs/reference/routes-file
// The filter must be valid for the MBTA endpoint, or the request will fail.
// E.g. `fetchRoutes` uses `type`, but `fetchPredictions` uses `route_type`.
const subwayRoutes = await mbta.fetchRoutes({ type: 'subway' });

// Filter by `direction_id` to only get results going in one direction.
// `direction_id` maps to the index of the route's `direction_names`.
// Example: Red line `direction_names` are `['South', 'North']`.
// Include `direction_id: 1` in options for Northbound results.
const north = await mbta.fetchPredictions({ route: 'Red', direction_id: 1 });

// Get results based on `latitude`/`longitude`, and optional `radius`.
const local = await mbta.fetchStops({ latitude: 42.373, longitude: -71.119 });

// Sort by `arrival_time`, `departure_time`, etc. See MBTA docs for each
// endpoint's sort options. `descending: true` will reverse sort order.
const sorted = await mbta.fetchPredictions({
  stop: 42,
  sort: 'arrival_time',
  descending: true,
});

// Alerts have a number of extra filters. See MBTA docs for best practices.
const alerts = await mbta.fetchAlerts({
  sort: 'cause',
  activity: 'BOARD',
  datetime: 'NOW',
  severity: [2, 3],
});

Helper functions:

Arrivals/Departures

Note: arrival and departure helpers have the same API/options.

// By default, returns an array of arrival times in ISO8601 format
const arr = mbta.selectArrivals(response);
// `convertTo` returns time left in ms, seconds, minutes, hours
const dep = mbta.selectDepartures(response, { convertTo: 'minutes' });

Fetch Helpers

// Returns basic info for all routes: name, ID, direction names.
// Useful when you need params for `fetchPredictions`, etc.
const allRouteInfo = await mbta.fetchAllRoutes();
console.log(allRouteInfo);

// Returns all stop IDs for the provided route. Also useful for params.
const redLineStops = await mbta.fetchStopsByRoute('Red');
console.log(redLineStops);

// Returns full MBTA response for stops with the provided string in the name.
// Optional param `{ exact: true }` returns only exact matches for the name.
const harvardStops = await mbta.fetchStopsByName('Harvard', { exact: true });
console.log(harvardStops);

Pagination

Helper functions fetch the first, next, previous and last pages.

// For paginated results, provide `limit` and optional `offset`
const results = await mbta.fetchPredictions({ stop: 42, limit: 2 });

// Use the result to fetch the next page
const secondPageResults = await mbta.fetchNextPage(results);
// Use the next page result to fetch the page after that
const thirdPageResults = await mbta.fetchNextPage(secondPageResults);
// Fetch first or last page from any result
const firstPageResults = await mbta.fetchFirstPage(results);
const lastPageResults = await mbta.fetchLastPage(results);

API

Fetch functions

These map to the endpoints listed in the MBTA docs. They return a promise that resolves to an MBTA response object. options for each function maps to the filters listed on that page. options that accept multiple values can be provided as an array or comma separated string.

mbta.fetchStops(options);
mbta.fetchTrips(options);
mbta.fetchRoutes(options);
mbta.fetchShapes(options);
mbta.fetchVehicles(options);
mbta.fetchServices(options);
mbta.fetchSchedules(options);
mbta.fetchFacilities(options);
mbta.fetchPredictions(options);
mbta.fetchLiveFacilities(options);

mbta.fetchAlerts(options); // See note on alerts below

The MBTA docs say: "Displaying alerts is one of the trickiest features to get correct." See their best practices and the alerts API docs for more information.

Helper functions

mbta.selectArrivals(response: MBTAResponse, options?: TimeOptions);
mbta.selectDepartures(response: MBTAResponse, options?: TimeOptions);

type TimeOptions = { convertTo?: 'ms' | 'seconds' | 'minutes' | 'hours' };

Note: arrival_time could be null if it's the first stop on a route. If departure_time is not null, the MBTA recommends using that instead. Departure could be null if it's the final stop on a route. See best practices for more info.

mbta.fetchAllRoutes(filters?: TypeOptions): Promise<BasicRouteResponse>;
mbta.fetchStopsByRoute(routeID: string|number): Promise<StopsByRouteResponse>;
mbta.fetchStopsByName(name: string, opts: NameOptions): Promise<MBTAResponse>;

mbta.selectIncluded(response: MBTAResponse, options?: TypeOptions);

type BasicRouteResponse = {
  id: string,
  long_name: string,
  direction_names: string[],
  short_name?: string
};
type StopsByRouteResponse = { name: string, id: string };
type TypeOptions = { type?: include_value | include_value[] };
type NameOptions = { exact: boolean };

See the MBTA API docs for include_value options for each endpoint

Pagination helpers

(These return a promise that resolves to an MBTA response object)

Note: Input must include links property.

mbta.fetchFirstPage(response: MBTAResponse);
mbta.fetchLastPage(response: MBTAResponse);
mbta.fetchNextPage(response: MBTAResponse);
mbta.fetchPrevPage(response: MBTAResponse);

MBTA API Documentation: https://api-v3.mbta.com/docs/swagger/index.html

MBTA API Best Practices: https://www.mbta.com/developers/v3-api/best-practices

Note: This library is not affiliated with the MBTA or MassDOT.

License

MIT