import { Observable, of, throwError } from 'rxjs'; import { MwOutput } from './middleware'; export function verifyResponse(output: MwOutput): Observable { const errors = getPreloadErrors((output || {}).response); return errors.length === 0 ? of(output) : throwError(new Error(`preload errors: ${errors.join(', ')}`)); } const kindHelp = 'can be one of `success`, `error`, `redirect` or `not-found`'; export function getPreloadErrors(resp: any): string[] { if (!resp || !resp.kind) return [`missing 'response.kind' - ${kindHelp}`]; if (resp.kind === 'success') return []; switch (resp.kind) { case 'success': return []; case 'error': { if (typeof resp.statusCode !== 'number' || typeof resp.message !== 'string') { return ['for an error, you must return a `statusCode` and a `message`']; } return []; } case 'redirect': { if (typeof resp.statusCode !== 'number' || typeof resp.location !== 'string') { return ['for a redirect, you must return a `statusCode` and a `location`']; } return []; } case 'not-found': { if (typeof resp.statusCode !== 'number') { return ['for a not-found response, you must return a `statusCode`']; } return []; } default: { return [`'${resp.kind}' is not a valid kind - ${kindHelp}`]; } } }