Skip to content

Commit

Permalink
flexibility with codes
Browse files Browse the repository at this point in the history
  • Loading branch information
tgoulder4 committed Aug 21, 2023
1 parent 0a271c7 commit f3c6957
Show file tree
Hide file tree
Showing 13 changed files with 20,662 additions and 42 deletions.
18 changes: 12 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# trainspy 2.0 🔍
[![Downloads](https://img.shields.io/npm/dt/trainspy?logo=npm&style=flat-square)](https://npmjs.com/package/trainspy) [![Discord](https://img.shields.io/badge/Discord-%235865F2.svg?style=for-the-badge&logo=discord&logoColor=white)](https://discord.gg/3bnnkvrZwc)

Get fast & free departures at any UK train station & recieve instant real-time updates on trains throughout their journey. Version 2.0 brings exact location tracking with precise latitude & longitude co-ordinates!

Expand All @@ -15,13 +16,16 @@ npm i trainspy
`findTrains(stationNameOrCode)` _-> Promise\<typeof Object>_

```js
const trains = await findTrains("WLF")
const moreTrains await findTrains("Solihull")
```
import { findTrains } from "trainspy";

_🌻 NOTE: Location co-ordinates are unavailable with use of a station name._
(async()=> {
const trains = await findTrains("WLF")
const moreTrains = await findTrains("Solihull")
console.log(trains);
})();
```

example response:
this yields a response:

```js
{
Expand Down Expand Up @@ -63,6 +67,8 @@ Emit live updates on a train until it's journey is complete. You first need the
E.g. ServiceID `P70052` departing on 18/08/2023:

```js
import { trackTrain } from "trainspy";

trackTrain("P70052", "2023-08-18").then((emitter) => {
emitter.on("journey", (update) => {
//your code for journey updates!
Expand Down Expand Up @@ -122,7 +128,7 @@ Journey updates
| ------------- | -----------------------|
| status | string |
| station | { `name`: string, `code`: string \| null, `location`: { `longitude`: number \| null, `latitude`: number \| null }`stopsHere`: boolean, `delay`: number \| null, `arrival`: { `actual`: string \| null, `scheduled`: string \| null }, `departure`: -same as arrival- } |
| callingPoints | Array\<Station> |
| callingPoints | Array\<station> |

Information updates
| Property | Type |
Expand Down
21 changes: 14 additions & 7 deletions dist/src/findTrains.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const getCurrentDayTime = require("./getDayTime");
const util = require("util");
const types_1 = require("./types/types");
var stationLocations = require("./map/stationLocations.json");
var stationCodes = require("./map/stationCodes.json");
const trackTrain_1 = require("./trackTrain");
//method: present stations
const findStationNameAndCode = (stationNameOrCode) => {
Expand All @@ -27,14 +28,21 @@ const findStationNameAndCode = (stationNameOrCode) => {
const match = stationNameOrCode.match(/^[A-Z]{3}$/);
if (match) {
// console.log(`match: ${match}`);
stationName = stationLocations[match[0]].station_name || null;
const jsonMatch = stationLocations[match[0]];
if (jsonMatch) {
stationName = stationLocations[match[0]].station_name;
stationCode = match[0];
}
else {
stationName = null;
stationCode = null;
}
// console.log(`stationName: ${stationName}`);
stationCode = match[0];
// console.log(`stationCode: ${stationCode}`);
}
else {
stationName = stationNameOrCode;
stationCode = null;
stationCode = stationCodes["stations"].find(station => station["Station Name"] == stationNameOrCode)["CRS Code"];
}
return { stationName, stationCode };
};
Expand All @@ -48,19 +56,18 @@ exports.findStationNameAndCode = findStationNameAndCode;
function findTrains(stationNameOrCode, dateOfDeparture = getCurrentDayTime("YYYY-MM-DD"), timeOfDeparture = getCurrentDayTime("HHmm")) {
return __awaiter(this, void 0, void 0, function* () {
//if stationName is 3 letters, destructure from map
const callOutAndInfoValue = yield fetch(`https://www.realtimetrains.co.uk/search/handler?location=${stationNameOrCode}`).then((res) => res.text().then((data) => {
const { stationName, stationCode } = (0, exports.findStationNameAndCode)(stationNameOrCode);
// console.log(`stationName: ${stationName}, stationCode: ${stationCode}`)
const callOutAndInfoValue = yield fetch(`https://www.realtimetrains.co.uk/search/handler?location=${stationCode}`).then((res) => res.text().then((data) => {
const $ = cheerio.load(data);
return { callout: $(".callout"), info: $(".info") };
}));
if (callOutAndInfoValue.callout.find("h3").text() ==
"Cannot find primary location" ||
callOutAndInfoValue.callout.find("p").text() ==
"Sorry, no services were found in the next two hours." ||
callOutAndInfoValue.info.find("h3").text() == "Bad request" ||
!stationNameOrCode) {
return (0, types_1.createInformationBodyResponse)("Error", "Please enter a valid station code or the date and time entered.");
}
const { stationName, stationCode } = (0, exports.findStationNameAndCode)(stationNameOrCode);
const location = {
latitude: stationCode ? stationLocations[stationCode].latitude : null,
longitude: stationCode ? stationLocations[stationCode].longitude : null,
Expand Down
15 changes: 13 additions & 2 deletions dist/src/getInfo.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
Object.defineProperty(exports, "__esModule", { value: true });
exports.getInfo = exports.getLocationObject = exports.parseStationNameAndCode = exports.getDelay = void 0;
var stationLocations = require("./map/stationLocations.json");
var stationCodes = require("./map/stationCodes.json");
//UNIT TESTS
function getDelay(record) {
if (record.find(".delay.nil").length != 0) {
Expand Down Expand Up @@ -31,8 +32,18 @@ function parseStationNameAndCode(stationString) {
};
}
exports.parseStationNameAndCode = parseStationNameAndCode;
function getLocationObject(code) {
if (stationLocations[code]) {
function getLocationObject(nameOrCode) {
//if it's a code
if (stationLocations[nameOrCode]) {
return {
latitude: stationLocations[nameOrCode].latitude,
longitude: stationLocations[nameOrCode].longitude,
};
}
//else find it's code
const stationObj = stationCodes["stations"].find((station) => station["Station Name"] == nameOrCode);
if (stationObj) {
const code = stationObj["CRS Code"];
return {
latitude: stationLocations[code].latitude,
longitude: stationLocations[code].longitude,
Expand Down
17 changes: 15 additions & 2 deletions dist/src/index.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,30 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const findTrains_1 = require("./findTrains");
const trackTrain_1 = require("./trackTrain");
// const util = require("util");
const util = require("util");
module.exports = {
findTrains: findTrains_1.default,
trackTrain: trackTrain_1.trackTrain,
};
// trackTrain("P71987", "2023-08-19").then((emitter) => {
// trackTrain("Smethwick Rolfe Street", "2023-08-19").then((emitter) => {
// emitter.on("journey", (data) => {
// console.log(util.inspect(data, false, null, true));
// });
// emitter.on("information", (data) => {
// console.log(util.inspect(data, false, null, true));
// });
// });
(() => __awaiter(void 0, void 0, void 0, function* () {
const data = yield (0, findTrains_1.default)("ABC", "2023-08-19");
console.log(util.inspect(data, false, null, true));
}))();
Loading

0 comments on commit f3c6957

Please sign in to comment.