-
Notifications
You must be signed in to change notification settings - Fork 43
Improvements #243
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
base: main
Are you sure you want to change the base?
Improvements #243
Changes from all commits
5b2a100
776995c
8fa674d
3fa7c26
9d1c721
4c81a26
10f2570
1a31cdd
dbe65a9
30dd70a
37a7091
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| { | ||
| "tabWidth": 2, | ||
| "useTabs": false | ||
| } | ||
| 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"]; | ||
| }; |
| 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"; | ||||||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
|
|
||||||
| 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) => { | ||||||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
| 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; | ||||||
| }; | ||||||
| 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)!; | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 |
||
|
|
||
| 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" }); | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.