107 lines
3.1 KiB
TypeScript
107 lines
3.1 KiB
TypeScript
import { PrismaClient } from '@prisma/client';
|
|
import fs from 'fs';
|
|
import * as turf from '@turf/turf';
|
|
|
|
export class GeoJSONSeeder {
|
|
constructor(private prisma: PrismaClient) {}
|
|
|
|
async run(): Promise<void> {
|
|
console.log('Seeding GeoJSON data...');
|
|
|
|
await this.prisma.$executeRaw`TRUNCATE TABLE "geographics" CASCADE`;
|
|
|
|
try {
|
|
// Load GeoJSON file
|
|
const regencyGeoJson = JSON.parse(
|
|
fs.readFileSync('prisma/data/geojson/jember/regency.geojson', 'utf-8')
|
|
);
|
|
const districtGeoJson = JSON.parse(
|
|
fs.readFileSync('prisma/data/geojson/jember/districts.geojson', 'utf-8')
|
|
);
|
|
|
|
// 1. Insert Kota/Kabupaten: Jember
|
|
let regency; // Declare regency variable outside the loop
|
|
|
|
for (const feature of regencyGeoJson.features) {
|
|
const properties = feature.properties;
|
|
const geometry = feature.geometry;
|
|
|
|
// Cleanup code
|
|
const regencyCode = properties.kode_kk.replace(/\./g, '');
|
|
|
|
// Insert Regency
|
|
regency = await this.prisma.cities.create({
|
|
data: {
|
|
id: regencyCode,
|
|
name: properties.kab_kota,
|
|
},
|
|
});
|
|
|
|
// Insert Geographics for Regency
|
|
const centroid = turf.centroid(feature);
|
|
const [longitude, latitude] = centroid.geometry.coordinates;
|
|
const area = turf.area(feature) / 1_000_000; // dari m² ke km²
|
|
|
|
await this.prisma.geographics.create({
|
|
data: {
|
|
city_id: regency.id,
|
|
latitude,
|
|
longitude,
|
|
land_area: area,
|
|
geometry: feature.geometry,
|
|
},
|
|
});
|
|
|
|
console.log(`Inserted regency: ${regency.name}`);
|
|
}
|
|
|
|
// 2. Loop Semua District di GeoJSON
|
|
for (const feature of districtGeoJson.features) {
|
|
const properties = feature.properties;
|
|
const geometry = feature.geometry;
|
|
|
|
// Cleanup code
|
|
const districtCode = properties.kode_kec.replace(/\./g, '');
|
|
|
|
// Insert District
|
|
const district = await this.prisma.districts.create({
|
|
data: {
|
|
id: districtCode,
|
|
name: properties.kecamatan,
|
|
city_id: regency!.id,
|
|
},
|
|
});
|
|
|
|
console.log(`Inserted district: ${district.name}`);
|
|
|
|
// 3. Hitung Centroid dan Area
|
|
const centroid = turf.centroid(feature);
|
|
const [longitude, latitude] = centroid.geometry.coordinates;
|
|
const area = turf.area(feature) / 1_000_000; // dari m² ke km²
|
|
|
|
// 4. Insert Geographics
|
|
await this.prisma.geographics.create({
|
|
data: {
|
|
city_id: regency!.id,
|
|
district_id: district.id,
|
|
latitude,
|
|
longitude,
|
|
land_area: area,
|
|
geometry: feature.geometry,
|
|
},
|
|
});
|
|
|
|
console.log(`Inserted geographics for district: ${district.name}`);
|
|
}
|
|
|
|
console.log(
|
|
'GeoJSON data seeded successfully!',
|
|
districtGeoJson.features.length,
|
|
'districts inserted.'
|
|
);
|
|
} catch (error) {
|
|
console.error('Error seeding GeoJSON data:', error);
|
|
}
|
|
}
|
|
}
|