|
1 | | -import { PutObjectCommand, S3Client } from '@aws-sdk/client-s3'; |
| 1 | +import { DeleteObjectCommand, ListObjectsV2Command, PutObjectCommand, S3Client } from '@aws-sdk/client-s3'; |
2 | 2 | import { createReadStream } from 'fs'; |
3 | 3 | import { getRepository } from 'typeorm'; |
4 | 4 | import GeojsonEncoder from '../business/geodata/GeojsonEncoder'; |
@@ -35,16 +35,66 @@ export default async function syncMap(): Promise<void> { |
35 | 35 |
|
36 | 36 | console.log('Uploading PMTiles to S3...'); |
37 | 37 | const pmtilesStream = createReadStream(result.outputPath); |
| 38 | + |
| 39 | + const key = `photos-1940s_${Date.now()}.pmtiles`; |
38 | 40 |
|
39 | 41 | await s3.send( |
40 | 42 | new PutObjectCommand({ |
41 | 43 | Bucket: 'fourties-maps', |
42 | | - Key: 'photos-1940s.pmtiles', |
| 44 | + Key: key, |
43 | 45 | Body: pmtilesStream, |
44 | 46 | ContentType: 'application/vnd.pmtiles', |
45 | 47 | CacheControl: 'max-age=86400', |
46 | 48 | }) |
47 | 49 | ); |
48 | 50 |
|
| 51 | + await s3.send( |
| 52 | + new PutObjectCommand({ |
| 53 | + Bucket: 'fourties-maps', |
| 54 | + Key: `photos-1940s_latest.pmtiles`, |
| 55 | + WebsiteRedirectLocation: `/${key}`, |
| 56 | + Body: undefined, |
| 57 | + ContentType: 'application/vnd.pmtiles', |
| 58 | + CacheControl: 'no-cache' |
| 59 | + }) |
| 60 | + ); |
| 61 | + |
| 62 | + // Save a version file that points to the latest PMTiles file |
| 63 | + const versionFileContent = JSON.stringify({ |
| 64 | + currentKey: key, |
| 65 | + }); |
| 66 | + await s3.send( |
| 67 | + new PutObjectCommand({ |
| 68 | + Bucket: 'fourties-maps', |
| 69 | + Key: 'photos-1940s_version.json', |
| 70 | + Body: versionFileContent, |
| 71 | + ContentType: 'application/json', |
| 72 | + CacheControl: 'no-cache', |
| 73 | + }) |
| 74 | + ); |
| 75 | + |
| 76 | + // Cleanup pmtiles older than 7 days |
| 77 | + console.log('Cleaning up old PMTiles files...'); |
| 78 | + const sevenDaysAgo = new Date(); |
| 79 | + sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7); |
| 80 | + |
| 81 | + const listCommand = new ListObjectsV2Command({ |
| 82 | + Bucket: 'fourties-maps', |
| 83 | + Prefix: 'photos-1940s_', |
| 84 | + }); |
| 85 | + const listResponse = await s3.send(listCommand); |
| 86 | + if (listResponse.Contents) { |
| 87 | + for (const item of listResponse.Contents) { |
| 88 | + if (item.Key && item.Key.endsWith('.pmtiles') && item.LastModified && item.LastModified < sevenDaysAgo) { |
| 89 | + console.log(`Deleting old PMTiles file: ${item.Key}`); |
| 90 | + const deleteCommand = new DeleteObjectCommand({ |
| 91 | + Bucket: 'fourties-maps', |
| 92 | + Key: item.Key, |
| 93 | + }); |
| 94 | + await s3.send(deleteCommand); |
| 95 | + } |
| 96 | + } |
| 97 | + } |
| 98 | + |
49 | 99 | console.log('Sync of map data complete.'); |
50 | 100 | } |
0 commit comments