Skip to content

Instantly share code, notes, and snippets.

@heggemsnes
Created February 7, 2024 13:52
Show Gist options
  • Save heggemsnes/0cb0c2863f9f0df5b7b77d740d3825bc to your computer and use it in GitHub Desktop.
Save heggemsnes/0cb0c2863f9f0df5b7b77d740d3825bc to your computer and use it in GitHub Desktop.
Create counties and municipalities for Norway in Sanity
import { authClient } from "../sanity/sanity-config.auth.server";
type Response = Fylke[];
interface Fylke {
avgrensningsboks: Avgrensningsboks;
fylkesnavn: string;
fylkesnummer: string;
kommuner: Kommuner[];
}
interface Avgrensningsboks {
coordinates: number[][][];
crs: Crs;
type: string;
}
interface Crs {
properties: Properties;
type: string;
}
interface Properties {
name: string;
}
interface Kommuner {
avgrensningsboks: Avgrensningsboks2;
fylkesnavn: string;
fylkesnummer: string;
gyldigeNavn: GyldigeNavn[];
kommunenavn: string;
kommunenavnNorsk: string;
kommunenummer: string;
punktIOmrade: PunktIomrade;
samiskForvaltningsomrade: boolean;
}
interface Avgrensningsboks2 {
coordinates: number[][][];
crs: Crs2;
type: string;
}
interface Crs2 {
properties: Properties2;
type: string;
}
interface Properties2 {
name: string;
}
interface GyldigeNavn {
navn: string;
prioritet: number;
sprak: string;
}
interface PunktIomrade {
coordinates: number[];
crs: Crs3;
type: string;
}
interface Crs3 {
properties: Properties3;
type: string;
}
interface Properties3 {
name: string;
}
export const getFylkerAndKommuner = async () => {
try {
const response = await fetch(
"https://api.kartverket.no/kommuneinfo/v1/fylkerkommuner",
);
if (!response.ok) {
throw new Error("Could not fetch data from Kartverket");
}
const data = await response.json();
console.log(data);
return data as Response;
} catch (error) {
console.error(error);
}
};
export const createFylkerAndKommuner = async () => {
const data = await getFylkerAndKommuner();
if (!data) return null;
const countyTransaction = authClient.transaction();
// Create all counties
for (const fylke of data) {
const county = {
_type: "county",
_id: `county-${fylke.fylkesnummer}`,
title: fylke.fylkesnavn,
countyNumber: fylke.fylkesnummer,
};
countyTransaction.createOrReplace(county);
}
const commited = await countyTransaction.commit();
// Create all municipalities
for (const fylke of data) {
const municipalityTransaction = authClient.transaction();
for (const kommune of fylke.kommuner) {
const municipality = {
_type: "municipality",
_id: `municipality-${kommune.kommunenummer}`,
title: kommune.kommunenavn,
municipalityNumber: kommune.kommunenummer,
active: false,
county: {
_type: "reference",
_ref: `county-${kommune.fylkesnummer}`,
},
};
municipalityTransaction.createOrReplace(municipality);
}
const created = await municipalityTransaction.commit();
console.log(
`Created ${created.results.length} municipalities for ${fylke.fylkesnavn}`,
);
}
return commited;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment