From c53e60e09099f445f7f483ea45bd19bf1a1670b9 Mon Sep 17 00:00:00 2001 From: Matthew Oslan Date: Sat, 6 Jul 2019 09:30:32 -0400 Subject: [PATCH] Split PWS ID and API key into 2 parameters --- routes/adjustmentMethods/AdjustmentMethod.ts | 4 +- routes/weather.ts | 44 +++++++++----------- 2 files changed, 23 insertions(+), 25 deletions(-) diff --git a/routes/adjustmentMethods/AdjustmentMethod.ts b/routes/adjustmentMethods/AdjustmentMethod.ts index 2e5e051..514dabe 100644 --- a/routes/adjustmentMethods/AdjustmentMethod.ts +++ b/routes/adjustmentMethods/AdjustmentMethod.ts @@ -57,6 +57,8 @@ export interface AdjustmentMethodResponse { } export interface AdjustmentOptions { - /** Information about the PWS to use in the format "pws:API_KEY@PWS_ID". */ + /** The ID of the PWS to use, prefixed with "pws:". */ pws?: string; + /** The API key to use to access PWS data. */ + key?: string; } diff --git a/routes/weather.ts b/routes/weather.ts index c0e7d21..c8feb0c 100644 --- a/routes/weather.ts +++ b/routes/weather.ts @@ -218,15 +218,29 @@ export const getWateringData = async function( req: express.Request, res: expres let timeData: TimeData = getTimeData( coordinates ); // Parse the PWS information. - const pwsString: string | undefined = adjustmentOptions.pws; let pws: PWS | undefined = undefined; - if ( pwsString ) { - try { - pws = parsePWS( pwsString ); - } catch ( err ) { - res.send( `Error: ${ err }` ); + if ( adjustmentOptions.pws ) { + if ( !adjustmentOptions.key ) { + res.send("Error: An API key must be provided when using a PWS."); return; } + + const idMatch = adjustmentOptions.pws.match( /^pws:([a-zA-Z\d]+)$/ ); + const pwsId = idMatch ? idMatch[ 1 ] : undefined; + const keyMatch = adjustmentOptions.key.match( /^[a-f\d]{32}$/ ); + const apiKey = keyMatch ? keyMatch[ 0 ] : undefined; + + // Make sure that the PWS ID and API key look valid. + if ( !pwsId ) { + res.send("Error: PWS ID does not appear to be valid."); + return; + } + if ( !apiKey ) { + res.send("Error: PWS API key does not appear to be valid."); + return; + } + + pws = { id: pwsId, apiKey: apiKey }; } const weatherProvider = pws ? PWS_WEATHER_PROVIDER : WEATHER_PROVIDER; @@ -474,21 +488,3 @@ function getParameter( parameter: string | string[] ): string { // Return an empty string if the parameter is undefined. return parameter || ""; } - -/** - * Creates a PWS object from a string. - * @param pwsString Information about the PWS in the format "pws:API_KEY@PWS_ID". - * @return The PWS specified by the string. - * @throws Throws an error message if the string is in an invalid format and cannot be parsed. - */ -function parsePWS( pwsString: string): PWS { - const match = pwsString.match( /^pws:([a-f\d]{32})@([a-zA-Z\d]+)$/ ); - if ( !match ) { - throw "Invalid PWS format."; - } - - return { - apiKey: match[ 1 ], - id: match[ 2 ] - }; -}