| @ -1,10 +1,70 @@ | |||||
| import { httpGet } from './mock-http-interface'; | import { httpGet } from './mock-http-interface'; | ||||
| // TODO define this type properly | |||||
| type TResult = any; | |||||
| // Keys accepted by the TResult type | |||||
| type Keys = 'Arnie Quote' | 'FAILURE'; | |||||
| // TResult (array of which to return) | |||||
| type TResult = { | |||||
| [K in Keys]?: string; | |||||
| } | |||||
| // Result returned by the httpGet method | |||||
| type getResult = { | |||||
| status: number, | |||||
| body: string, | |||||
| } | |||||
| // The body of the getResult type, when decoded from json string | |||||
| type getResultBody = { | |||||
| message: string, | |||||
| } | |||||
| /** | |||||
| * Get and parse results from the mock http server | |||||
| * Note: I went a little overboard with the comments, so you know how I was thinking about this | |||||
| * | |||||
| * @param {string[]} url | |||||
| * @return {Promise<TResult[]>} | |||||
| */ | |||||
| export const getArnieQuotes = async (urls : string[]) : Promise<TResult[]> => { | export const getArnieQuotes = async (urls : string[]) : Promise<TResult[]> => { | ||||
| // TODO: Implement this function. | |||||
| return []; | |||||
| // Array to return | |||||
| let t_results: TResult[] = []; | |||||
| // All needing to resolve before returning (using Promise.all(promises)) | |||||
| let promises: Promise<void>[] = []; | |||||
| // Iterate through all urls | |||||
| for (let url of urls) { | |||||
| // Get the data from the url | |||||
| let promise: Promise<void> = httpGet(url) | |||||
| .then((result: getResult) => { | |||||
| // Determine whether the mock api call was successful | |||||
| let getResultKey: Keys = 'FAILURE'; | |||||
| if (result.status === 200) { | |||||
| getResultKey = 'Arnie Quote'; | |||||
| } | |||||
| // Decode the result_body | |||||
| let result_body: getResultBody = JSON.parse(result.body); | |||||
| // Push the results to the return array | |||||
| t_results.push({ | |||||
| [getResultKey]: result_body.message, | |||||
| } as TResult); | |||||
| // Resolve the promise after we are done | |||||
| return Promise.resolve(); | |||||
| }); | |||||
| // Push the promise to the "promises" array | |||||
| promises.push(promise); | |||||
| } | |||||
| // Wait for all promises to resolve | |||||
| await Promise.all(promises); | |||||
| // Return the data | |||||
| return t_results; | |||||
| }; | }; | ||||