Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improvements #243

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
4 changes: 4 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"tabWidth": 2,
"useTabs": false
}
ptbrowne marked this conversation as resolved.
Show resolved Hide resolved
56 changes: 56 additions & 0 deletions website/src/pages/api/_generate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { promises as fs } from "fs";
import * as mapshaper from "mapshaper";
import * as path from "path";

export const generate = async ({
format,
shapes,
simplify,
year,
mapshaperCommands,
}: {
format: "topojson" | "svg";
shapes: string[];
simplify: string;
mapshaperCommands?: string[];
year: string;
}) => {
const input = await (async () => {
const props = [...shapes].flatMap((shape) => {
return ["shp", "dbf", "prj"].map(
async (ext) =>
[
`${shape}.${ext}`,
await fs.readFile(
path.join(
process.cwd(),
"public/swiss-maps",
year,
`${shape}.${ext}`
)
),
] as const
);
});
return Object.fromEntries(await Promise.all(props));
})();

const inputFiles = [...shapes].map((shape) => `${shape}.shp`).join(" ");

const commands = [
`-i ${inputFiles} combine-files string-fields=*`,
simplify ? `-simplify ${simplify} keep-shapes` : "",
"-clean",
`-proj ${format === "topojson" ? "wgs84" : "somerc"}`,
...(mapshaperCommands || []),
].join("\n");

console.log("### Mapshaper commands ###");
console.log(commands);

const output = await mapshaper.applyCommands(commands, input);

return format === "topojson"
? output["output.topojson"]
: output["output.svg"];
};
114 changes: 114 additions & 0 deletions website/src/pages/api/_utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import { either } from "fp-ts";
import produce from "immer";
import * as t from "io-ts";
import { NextApiRequest, NextApiResponse } from "next";
import { defaultOptions, Shape } from "src/shared";
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
import { defaultOptions, Shape } from "src/shared";
import { defaultOptions, Options, Shape } from "src/shared";


type Format = "topojson" | "svg";

export const formatExtensions = {
topojson: "json",
svg: "svg",
} as Record<Format, string>;

export const formatContentTypes = {
topojson: "application/json",
svg: "image/svg+xml",
} as Record<Format, string>;

const Query = t.type({
format: t.union([t.undefined, t.literal("topojson"), t.literal("svg")]),
year: t.union([t.undefined, t.string]),
shapes: t.union([t.undefined, t.string]),
simplify: t.union([t.undefined, t.string]),
download: t.union([t.undefined, t.string]),
});

export const parseOptions = (req: NextApiRequest, res: NextApiResponse) => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
export const parseOptions = (req: NextApiRequest, res: NextApiResponse) => {
export const parseOptions = (req: NextApiRequest, res: NextApiResponse): undefined | Options => {

const query = either.getOrElseW<unknown, undefined>(() => undefined)(
Query.decode(req.query)
);

if (!query) {
res.statusCode = 200;
res.setHeader("Content-Type", "text/plain");
res.end("Failed to decode query");
return;
}

if (!query.shapes) {
res.setHeader("Content-Type", "text/plain");
res.status(204).send("0");
return;
}

const options = produce(defaultOptions, (draft) => {
if (query.year) {
draft.year = query.year;
}
if (query.format) {
draft.format = query.format;
}
if (query.shapes) {
draft.shapes = new Set<Shape>(query.shapes.split(",") as $FixMe);
}
});

return options;
};

export function initMiddleware(middleware: $FixMe) {
return (req: NextApiRequest, res: NextApiResponse) =>
new Promise((resolve, reject) => {
middleware(req, res, (result: unknown) => {
if (result instanceof Error) {
return reject(result);
}
return resolve(result);
});
});
}

const truthy = <T>(x: T): x is Exclude<T, undefined | null> => {
return Boolean(x);
};

export const makeMapshaperStyleCommands = (
shapeStyles: Record<
string,
null | {
fill?: string;
stroke?: string;
}
>
) => {
return Object.entries(shapeStyles)
.map(([shapeName, style]) => {
if (style === null) {
return style;
}
return `-style target='${shapeName}' ${Object.entries(style)
.map(([propName, propValue]) => {
return `${propName}='${propValue}'`;
})
.join(" ")}`;
})
.filter(truthy);
};

const getShapeZIndex = (shape: string) => {
if (shape.includes("country")) {
return 3;
} else if (shape.includes("cantons")) {
return 2;
} else if (shape.includes("lakes")) {
return 1;
}
return 0;
};

export const shapeIndexComparator = (a: string, b: string) => {
const za = getShapeZIndex(a);
const zb = getShapeZIndex(b);
return za === zb ? 0 : za < zb ? -1 : 1;
};
139 changes: 28 additions & 111 deletions website/src/pages/api/generate.ts
Original file line number Diff line number Diff line change
@@ -1,138 +1,55 @@
import Cors from "cors";
import { either } from "fp-ts";
import { promises as fs } from "fs";
import { enableMapSet, produce } from "immer";
import * as t from "io-ts";
import * as mapshaper from "mapshaper";
import { enableMapSet } from "immer";
import { NextApiRequest, NextApiResponse } from "next";
import * as path from "path";
import { defaultOptions, Shape } from "src/shared";
import { generate } from "./_generate";
import {
formatContentTypes,
formatExtensions,
initMiddleware,
parseOptions,
shapeIndexComparator,
} from "./_utils";

enableMapSet();

async function get(url: string) {
return fetch(url)
.then((res) => res.arrayBuffer())
.then((ab) => Buffer.from(ab));
}

function initMiddleware(middleware: $FixMe) {
return (req: NextApiRequest, res: NextApiResponse) =>
new Promise((resolve, reject) => {
middleware(req, res, (result: unknown) => {
if (result instanceof Error) {
return reject(result);
}
return resolve(result);
});
});
}

const cors = initMiddleware(
Cors({
methods: ["GET", "POST", "OPTIONS"],
})
);

const Query = t.type({
format: t.union([t.undefined, t.literal("topojson"), t.literal("svg")]),
year: t.union([t.undefined, t.string]),
shapes: t.union([t.undefined, t.string]),
simplify: t.union([t.undefined, t.string]),
download: t.union([t.undefined, t.string]),
});

export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
try {
await cors(req, res);

const query = either.getOrElseW<unknown, undefined>(() => undefined)(
Query.decode(req.query)
);

if (!query) {
res.statusCode = 200;
res.setHeader("Content-Type", "text/plain");
res.end("Failed to decode query");
return;
}

const options = produce(defaultOptions, (draft) => {
if (query.year) {
draft.year = query.year;
}
if (query.format) {
draft.format = query.format;
}
const { query } = req;
const options = parseOptions(req, res)!;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The parseOptions function ends the response (and if it does it returns undefined). So if options is undefined the handler should exit, otherwise it'll try to write into an already closed response.


if (query.shapes) {
draft.shapes = new Set<Shape>(query.shapes.split(",") as $FixMe);
}
});
const { format, year, shapes } = options;
// console.log(year, shapes);

const input = await (async () => {
const props = [...shapes].flatMap((shape) => {
return ["shp", "dbf", "prj"].map(
async (ext) =>
[
`${shape}.${ext}`,
await fs.readFile(
path.join(
process.cwd(),
"public",
"swiss-maps",
year,
`${shape}.${ext}`
)
),
] as const
);
});
return Object.fromEntries(await Promise.all(props));
})();

const inputFiles = [...shapes].map((shape) => `${shape}.shp`).join(" ");

const commands = [
`-i ${inputFiles} combine-files string-fields=*`,
// `-rename-layers ${shp.join(",")}`,
query.simplify ? `-simplify ${query.simplify} keep-shapes` : "",
"-clean",
`-proj ${format === "topojson" ? "wgs84" : "somerc"}`,
`-o output.${format} format=${format} drop-table id-field=id`,
].join("\n");

console.log("### Mapshaper commands ###");
console.log(commands);

const output = await mapshaper.applyCommands(commands, input);

if (format === "topojson") {
if (query.download !== undefined) {
res.setHeader(
"Content-Disposition",
`attachment; filename="swiss-maps.json"`
);
}

res.setHeader("Content-Type", "application/json");
res.status(200).send(output["output.topojson"]);
} else if (format === "svg") {
res.setHeader("Content-Type", "image/svg+xml");
const output = await generate({
...options,
year,
simplify: query.simplify as string,
shapes: [...shapes].sort(shapeIndexComparator),
mapshaperCommands: [
`-o output.${format} format=${format} drop-table id-field=id target=*`,
],
});

if (query.download !== undefined) {
res.setHeader(
"Content-Disposition",
`attachment; filename="swiss-maps.svg"`
);
}
res.status(200).send(output["output.svg"]);
if (query.download !== undefined) {
res.setHeader(
"Content-Disposition",
`attachment; filename="swiss-maps.${formatExtensions[format]}"`
);
}

res.setHeader("Content-Type", formatContentTypes[format]);
res.status(200).send(output);
} catch (e) {
console.error(e);
res.status(500).json({ message: "Internal error" });
Expand Down
Loading