diff --git a/api/app/controllers/postcodes_controller.ts b/api/app/controllers/postcodes_controller.ts index d4a686f7..e7348e86 100644 --- a/api/app/controllers/postcodes_controller.ts +++ b/api/app/controllers/postcodes_controller.ts @@ -1,5 +1,6 @@ import { isEmpty, qToString } from "../lib/string"; import { Postcode } from "../models/postcode"; +import { TerminatedPostcode } from "../models/terminated_postcode"; import { isValid } from "postcode"; import { chunk } from "../lib/chunk"; import { getConfig } from "../../config/config"; @@ -29,7 +30,11 @@ export const show: Handler = async (request, response, next) => { if (!isValid(postcode.trim())) throw new InvalidPostcodeError(); const result = await Postcode.find(postcode); - if (!result) throw new PostcodeNotFoundError(); + if (!result) { + // Check if postcode has been terminated + const terminated = await TerminatedPostcode.find(postcode); + throw new PostcodeNotFoundError(terminated); + } response.jsonApiResponse = { status: 200, result: Postcode.toJson(result) }; next(); } catch (error) { diff --git a/api/app/lib/errors.ts b/api/app/lib/errors.ts index e2ac1236..46565d81 100644 --- a/api/app/lib/errors.ts +++ b/api/app/lib/errors.ts @@ -64,9 +64,44 @@ export class InvalidPostcodeError extends PostcodesioHttpError { } } +interface TerminatedPostcodeTuple { + id: number; + postcode: string; + pc_compact: string; + year_terminated: number; + month_terminated: number; + eastings: number; + northings: number; + longitude: number; + latitude: number; + location: string; +} + export class PostcodeNotFoundError extends PostcodesioHttpError { - constructor() { + public terminatedPostcode: TerminatedPostcodeTuple | null; + + constructor(terminatedPostcode: TerminatedPostcodeTuple | null = null) { super(404, "Postcode not found"); + Object.setPrototypeOf(this, PostcodeNotFoundError.prototype); + this.terminatedPostcode = terminatedPostcode; + } + + toJSON() { + const terminated = this.terminatedPostcode + ? { + postcode: this.terminatedPostcode.postcode, + year_terminated: this.terminatedPostcode.year_terminated, + month_terminated: this.terminatedPostcode.month_terminated, + longitude: this.terminatedPostcode.longitude, + latitude: this.terminatedPostcode.latitude, + } + : null; + + return { + status: this.status, + error: this.humanMessage, + ...(terminated !== null && { terminated }), + }; } } diff --git a/build/404.html b/build/404.html index 03497c12..f1410db0 100644 --- a/build/404.html +++ b/build/404.html @@ -4,8 +4,8 @@