-
-
Notifications
You must be signed in to change notification settings - Fork 229
/
apiRouter.ts
3872 lines (3486 loc) · 122 KB
/
apiRouter.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint @typescript-eslint/no-unused-vars: [ "warn", { argsIgnorePattern: "^(res|req)$" } ] */
import * as lodash from "lodash"
import * as db from "../db/db.js"
import {
UNCATEGORIZED_TAG_ID,
BAKE_ON_CHANGE,
BAKED_BASE_URL,
ADMIN_BASE_URL,
DATA_API_URL,
FEATURE_FLAGS,
} from "../settings/serverSettings.js"
import {
CLOUDFLARE_IMAGES_URL,
FeatureFlagFeature,
} from "../settings/clientSettings.js"
import { expectInt, isValidSlug } from "../serverUtils/serverUtil.js"
import {
OldChartFieldList,
assignTagsForCharts,
getChartConfigById,
getChartSlugById,
getGptTopicSuggestions,
getRedirectsByChartId,
oldChartFieldList,
setChartTags,
getParentByChartConfig,
getPatchConfigByChartId,
isInheritanceEnabledForChart,
getParentByChartId,
} from "../db/model/Chart.js"
import { Request } from "./authentication.js"
import {
getMergedGrapherConfigForVariable,
fetchS3MetadataByPath,
fetchS3DataValuesByPath,
searchVariables,
getGrapherConfigsForVariable,
updateGrapherConfigAdminOfVariable,
updateGrapherConfigETLOfVariable,
updateAllChartsThatInheritFromIndicator,
updateAllMultiDimViewsThatInheritFromIndicator,
getAllChartsForIndicator,
} from "../db/model/Variable.js"
import { updateExistingFullConfig } from "../db/model/ChartConfigs.js"
import { getCanonicalUrl } from "@ourworldindata/components"
import {
GDOCS_BASE_URL,
camelCaseProperties,
GdocsContentSource,
isEmpty,
JsonError,
OwidGdocPostInterface,
parseIntOrUndefined,
DbRawPostWithGdocPublishStatus,
OwidVariableWithSource,
TaggableType,
DbChartTagJoin,
pick,
Json,
checkIsGdocPostExcludingFragments,
checkIsPlainObjectWithGuard,
mergeGrapherConfigs,
diffGrapherConfigs,
omitUndefinedValues,
getParentVariableIdFromChartConfig,
omit,
gdocUrlRegex,
} from "@ourworldindata/utils"
import { applyPatch } from "../adminShared/patchHelper.js"
import {
OperationContext,
parseToOperation,
} from "../adminShared/SqlFilterSExpression.js"
import {
BulkChartEditResponseRow,
BulkGrapherConfigResponse,
chartBulkUpdateAllowedColumnNamesAndTypes,
GrapherConfigPatch,
variableAnnotationAllowedColumnNamesAndTypes,
VariableAnnotationsResponseRow,
} from "../adminShared/AdminSessionTypes.js"
import {
DbPlainDatasetTag,
GrapherInterface,
OwidGdocType,
DbPlainUser,
UsersTableName,
DbPlainTag,
DbRawVariable,
parseOriginsRow,
PostsTableName,
DbRawPost,
DbPlainChartSlugRedirect,
DbPlainChart,
DbInsertChartRevision,
serializeChartConfig,
DbRawOrigin,
DbRawPostGdoc,
PostsGdocsXImagesTableName,
PostsGdocsLinksTableName,
PostsGdocsTableName,
DbPlainDataset,
DbInsertUser,
FlatTagGraph,
DbRawChartConfig,
parseChartConfig,
MultiDimDataPageConfigRaw,
R2GrapherConfigDirectory,
ChartConfigsTableName,
Base64String,
DbPlainChartView,
ChartViewsTableName,
DbInsertChartView,
PostsGdocsComponentsTableName,
CHART_VIEW_PROPS_TO_PERSIST,
CHART_VIEW_PROPS_TO_OMIT,
DbEnrichedImage,
JsonString,
} from "@ourworldindata/types"
import { uuidv7 } from "uuidv7"
import {
migrateGrapherConfigToLatestVersion,
getVariableDataRoute,
getVariableMetadataRoute,
defaultGrapherConfig,
grapherConfigToQueryParams,
} from "@ourworldindata/grapher"
import { getDatasetById, setTagsForDataset } from "../db/model/Dataset.js"
import { getUserById, insertUser, updateUser } from "../db/model/User.js"
import { GdocPost } from "../db/model/Gdoc/GdocPost.js"
import {
syncDatasetToGitRepo,
removeDatasetFromGitRepo,
} from "./gitDataExport.js"
import { denormalizeLatestCountryData } from "../baker/countryProfiles.js"
import {
indexIndividualGdocPost,
removeIndividualGdocPostFromIndex,
} from "../baker/algolia/utils/pages.js"
import { ChartViewMinimalInformation } from "../adminSiteClient/ChartEditor.js"
import { DeployQueueServer } from "../baker/DeployQueueServer.js"
import { FunctionalRouter } from "./FunctionalRouter.js"
import Papa from "papaparse"
import {
setTagsForPost,
getTagsByPostId,
getWordpressPostReferencesByChartId,
getGdocsPostReferencesByChartId,
} from "../db/model/Post.js"
import {
checkHasChanges,
checkIsLightningUpdate,
GdocPublishingAction,
getPublishingAction,
} from "../adminSiteClient/gdocsDeploy.js"
import { createGdocAndInsertOwidGdocPostContent } from "../db/model/Gdoc/archieToGdoc.js"
import { logErrorAndMaybeSendToBugsnag } from "../serverUtils/errorLog.js"
import {
getRouteWithROTransaction,
deleteRouteWithRWTransaction,
putRouteWithRWTransaction,
postRouteWithRWTransaction,
patchRouteWithRWTransaction,
getRouteNonIdempotentWithRWTransaction,
} from "./functionalRouterHelpers.js"
import { getPublishedLinksTo } from "../db/model/Link.js"
import {
getChainedRedirect,
getRedirectById,
getRedirects,
redirectWithSourceExists,
} from "../db/model/Redirect.js"
import { getMinimalGdocPostsByIds } from "../db/model/Gdoc/GdocBase.js"
import {
GdocLinkUpdateMode,
createOrLoadGdocById,
gdocFromJSON,
getAllGdocIndexItemsOrderedByUpdatedAt,
getAndLoadGdocById,
getGdocBaseObjectById,
setLinksForGdoc,
setTagsForGdoc,
addImagesToContentGraph,
updateGdocContentOnly,
upsertGdoc,
} from "../db/model/Gdoc/GdocFactory.js"
import { match } from "ts-pattern"
import { GdocDataInsight } from "../db/model/Gdoc/GdocDataInsight.js"
import { GdocHomepage } from "../db/model/Gdoc/GdocHomepage.js"
import { GdocAbout } from "../db/model/Gdoc/GdocAbout.js"
import { GdocAuthor } from "../db/model/Gdoc/GdocAuthor.js"
import path from "path"
import {
deleteGrapherConfigFromR2,
deleteGrapherConfigFromR2ByUUID,
saveGrapherConfigToR2ByUUID,
} from "./chartConfigR2Helpers.js"
import { createMultiDimConfig } from "./multiDim.js"
import { isMultiDimDataPagePublished } from "../db/model/MultiDimDataPage.js"
import {
retrieveChartConfigFromDbAndSaveToR2,
saveNewChartConfigInDbAndR2,
updateChartConfigInDbAndR2,
} from "./chartConfigHelpers.js"
import { ApiChartViewOverview } from "../adminShared/AdminTypes.js"
import { References } from "../adminSiteClient/AbstractChartEditor.js"
import {
deleteFromCloudflare,
fetchGptGeneratedAltText,
processImageContent,
uploadToCloudflare,
validateImagePayload,
} from "./imagesHelpers.js"
import pMap from "p-map"
const apiRouter = new FunctionalRouter()
// Call this to trigger build and deployment of static charts on change
const triggerStaticBuild = async (user: DbPlainUser, commitMessage: string) => {
if (!BAKE_ON_CHANGE) {
console.log(
"Not triggering static build because BAKE_ON_CHANGE is false"
)
return
}
return new DeployQueueServer().enqueueChange({
timeISOString: new Date().toISOString(),
authorName: user.fullName,
authorEmail: user.email,
message: commitMessage,
})
}
const enqueueLightningChange = async (
user: DbPlainUser,
commitMessage: string,
slug: string
) => {
if (!BAKE_ON_CHANGE) {
console.log(
"Not triggering static build because BAKE_ON_CHANGE is false"
)
return
}
return new DeployQueueServer().enqueueChange({
timeISOString: new Date().toISOString(),
authorName: user.fullName,
authorEmail: user.email,
message: commitMessage,
slug,
})
}
async function getLogsByChartId(
knex: db.KnexReadonlyTransaction,
chartId: number
): Promise<
{
userId: number
config: Json
userName: string
createdAt: Date
}[]
> {
const logs = await db.knexRaw<{
userId: number
config: string
userName: string
createdAt: Date
}>(
knex,
`SELECT userId, config, fullName as userName, l.createdAt
FROM chart_revisions l
LEFT JOIN users u on u.id = userId
WHERE chartId = ?
ORDER BY l.id DESC
LIMIT 50`,
[chartId]
)
return logs.map((log) => ({
...log,
config: JSON.parse(log.config),
}))
}
const getReferencesByChartId = async (
chartId: number,
knex: db.KnexReadonlyTransaction
): Promise<References> => {
const postsWordpressPromise = getWordpressPostReferencesByChartId(
chartId,
knex
)
const postGdocsPromise = getGdocsPostReferencesByChartId(chartId, knex)
const explorerSlugsPromise = db.knexRaw<{ explorerSlug: string }>(
knex,
`SELECT DISTINCT
explorerSlug
FROM
explorer_charts
WHERE
chartId = ?`,
[chartId]
)
const chartViewsPromise = db.knexRaw<ChartViewMinimalInformation>(
knex,
`-- sql
SELECT cv.id, cv.name, cc.full ->> "$.title" AS title
FROM chart_views cv
JOIN chart_configs cc ON cc.id = cv.chartConfigId
WHERE cv.parentChartId = ?`,
[chartId]
)
const [postsWordpress, postsGdocs, explorerSlugs, chartViews] =
await Promise.all([
postsWordpressPromise,
postGdocsPromise,
explorerSlugsPromise,
chartViewsPromise,
])
return {
postsGdocs,
postsWordpress,
explorers: explorerSlugs.map(
(row: { explorerSlug: string }) => row.explorerSlug
),
chartViews,
}
}
const expectChartById = async (
knex: db.KnexReadonlyTransaction,
chartId: any
): Promise<GrapherInterface> => {
const chart = await getChartConfigById(knex, expectInt(chartId))
if (chart) return chart.config
throw new JsonError(`No chart found for id ${chartId}`, 404)
}
const expectPatchConfigByChartId = async (
knex: db.KnexReadonlyTransaction,
chartId: any
): Promise<GrapherInterface> => {
const patchConfig = await getPatchConfigByChartId(knex, expectInt(chartId))
if (!patchConfig) {
throw new JsonError(`No chart found for id ${chartId}`, 404)
}
return patchConfig
}
const saveNewChart = async (
knex: db.KnexReadWriteTransaction,
{
config,
user,
// new charts inherit by default
shouldInherit = true,
}: { config: GrapherInterface; user: DbPlainUser; shouldInherit?: boolean }
): Promise<{
chartConfigId: Base64String
patchConfig: GrapherInterface
fullConfig: GrapherInterface
}> => {
// grab the parent of the chart if inheritance should be enabled
const parent = shouldInherit
? await getParentByChartConfig(knex, config)
: undefined
// compute patch and full configs
const patchConfig = diffGrapherConfigs(config, parent?.config ?? {})
const fullConfig = mergeGrapherConfigs(parent?.config ?? {}, patchConfig)
// insert patch & full configs into the chart_configs table
// We can't quite use `saveNewChartConfigInDbAndR2` here, because
// we need to update the chart id in the config after inserting it.
const chartConfigId = uuidv7() as Base64String
await db.knexRaw(
knex,
`-- sql
INSERT INTO chart_configs (id, patch, full)
VALUES (?, ?, ?)
`,
[
chartConfigId,
serializeChartConfig(patchConfig),
serializeChartConfig(fullConfig),
]
)
// add a new chart to the charts table
const result = await db.knexRawInsert(
knex,
`-- sql
INSERT INTO charts (configId, isInheritanceEnabled, lastEditedAt, lastEditedByUserId)
VALUES (?, ?, ?, ?)
`,
[chartConfigId, shouldInherit, new Date(), user.id]
)
// The chart config itself has an id field that should store the id of the chart - update the chart now so this is true
const chartId = result.insertId
patchConfig.id = chartId
fullConfig.id = chartId
await db.knexRaw(
knex,
`-- sql
UPDATE chart_configs cc
JOIN charts c ON c.configId = cc.id
SET
cc.patch=JSON_SET(cc.patch, '$.id', ?),
cc.full=JSON_SET(cc.full, '$.id', ?)
WHERE c.id = ?
`,
[chartId, chartId, chartId]
)
await retrieveChartConfigFromDbAndSaveToR2(knex, chartConfigId)
return { chartConfigId, patchConfig, fullConfig }
}
const updateExistingChart = async (
knex: db.KnexReadWriteTransaction,
params: {
config: GrapherInterface
user: DbPlainUser
chartId: number
// if undefined, keep inheritance as is.
// if true or false, enable or disable inheritance
shouldInherit?: boolean
}
): Promise<{
chartConfigId: Base64String
patchConfig: GrapherInterface
fullConfig: GrapherInterface
}> => {
const { config, user, chartId } = params
// make sure that the id of the incoming config matches the chart id
config.id = chartId
// if inheritance is enabled, grab the parent from its config
const shouldInherit =
params.shouldInherit ??
(await isInheritanceEnabledForChart(knex, chartId))
const parent = shouldInherit
? await getParentByChartConfig(knex, config)
: undefined
// compute patch and full configs
const patchConfig = diffGrapherConfigs(config, parent?.config ?? {})
const fullConfig = mergeGrapherConfigs(parent?.config ?? {}, patchConfig)
const chartConfigIdRow = await db.knexRawFirst<
Pick<DbPlainChart, "configId">
>(knex, `SELECT configId FROM charts WHERE id = ?`, [chartId])
if (!chartConfigIdRow)
throw new JsonError(`No chart config found for id ${chartId}`, 404)
const now = new Date()
const { chartConfigId } = await updateChartConfigInDbAndR2(
knex,
chartConfigIdRow.configId as Base64String,
patchConfig,
fullConfig
)
// update charts row
await db.knexRaw(
knex,
`-- sql
UPDATE charts
SET isInheritanceEnabled=?, updatedAt=?, lastEditedAt=?, lastEditedByUserId=?
WHERE id = ?
`,
[shouldInherit, now, now, user.id, chartId]
)
return { chartConfigId, patchConfig, fullConfig }
}
const saveGrapher = async (
knex: db.KnexReadWriteTransaction,
{
user,
newConfig,
existingConfig,
shouldInherit,
referencedVariablesMightChange = true,
}: {
user: DbPlainUser
newConfig: GrapherInterface
existingConfig?: GrapherInterface
// if undefined, keep inheritance as is.
// if true or false, enable or disable inheritance
shouldInherit?: boolean
// if the variables a chart uses can change then we need
// to update the latest country data which takes quite a long time (hundreds of ms)
referencedVariablesMightChange?: boolean
}
) => {
// Try to migrate the new config to the latest version
newConfig = migrateGrapherConfigToLatestVersion(newConfig)
// Slugs need some special logic to ensure public urls remain consistent whenever possible
async function isSlugUsedInRedirect() {
const rows = await db.knexRaw<DbPlainChartSlugRedirect>(
knex,
`SELECT * FROM chart_slug_redirects WHERE chart_id != ? AND slug = ?`,
// -1 is a placeholder ID that will never exist; but we cannot use NULL because
// in that case we would always get back an empty resultset
[existingConfig ? existingConfig.id : -1, newConfig.slug]
)
return rows.length > 0
}
async function isSlugUsedInOtherGrapher() {
const rows = await db.knexRaw<Pick<DbPlainChart, "id">>(
knex,
`-- sql
SELECT c.id
FROM charts c
JOIN chart_configs cc ON cc.id = c.configId
WHERE
c.id != ?
AND cc.full ->> "$.isPublished" = "true"
AND cc.slug = ?
`,
// -1 is a placeholder ID that will never exist; but we cannot use NULL because
// in that case we would always get back an empty resultset
[existingConfig ? existingConfig.id : -1, newConfig.slug]
)
return rows.length > 0
}
// When a chart is published, check for conflicts
if (newConfig.isPublished) {
if (!isValidSlug(newConfig.slug))
throw new JsonError(`Invalid chart slug ${newConfig.slug}`)
else if (await isSlugUsedInRedirect())
throw new JsonError(
`This chart slug was previously used by another chart: ${newConfig.slug}`
)
else if (await isSlugUsedInOtherGrapher())
throw new JsonError(
`This chart slug is in use by another published chart: ${newConfig.slug}`
)
else if (
existingConfig &&
existingConfig.isPublished &&
existingConfig.slug !== newConfig.slug
) {
// Changing slug of an existing chart, delete any old redirect and create new one
await db.knexRaw(
knex,
`DELETE FROM chart_slug_redirects WHERE chart_id = ? AND slug = ?`,
[existingConfig.id, existingConfig.slug]
)
await db.knexRaw(
knex,
`INSERT INTO chart_slug_redirects (chart_id, slug) VALUES (?, ?)`,
[existingConfig.id, existingConfig.slug]
)
// When we rename grapher configs, make sure to delete the old one (the new one will be saved below)
await deleteGrapherConfigFromR2(
R2GrapherConfigDirectory.publishedGrapherBySlug,
`${existingConfig.slug}.json`
)
}
}
if (existingConfig)
// Bump chart version, very important for cachebusting
newConfig.version = existingConfig.version! + 1
else if (newConfig.version)
// If a chart is republished, we want to keep incrementing the old version number,
// otherwise it can lead to clients receiving cached versions of the old data.
newConfig.version += 1
else newConfig.version = 1
// add the isPublished field if is missing
if (newConfig.isPublished === undefined) {
newConfig.isPublished = false
}
// Execute the actual database update or creation
let chartId: number
let chartConfigId: Base64String
let patchConfig: GrapherInterface
let fullConfig: GrapherInterface
if (existingConfig) {
chartId = existingConfig.id!
const configs = await updateExistingChart(knex, {
config: newConfig,
user,
chartId,
shouldInherit,
})
chartConfigId = configs.chartConfigId
patchConfig = configs.patchConfig
fullConfig = configs.fullConfig
} else {
const configs = await saveNewChart(knex, {
config: newConfig,
user,
shouldInherit,
})
chartConfigId = configs.chartConfigId
patchConfig = configs.patchConfig
fullConfig = configs.fullConfig
chartId = fullConfig.id!
}
// Record this change in version history
const chartRevisionLog = {
chartId: chartId as number,
userId: user.id,
config: serializeChartConfig(patchConfig),
createdAt: new Date(),
updatedAt: new Date(),
} satisfies DbInsertChartRevision
await db.knexRaw(
knex,
`INSERT INTO chart_revisions (chartId, userId, config, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?)`,
[
chartRevisionLog.chartId,
chartRevisionLog.userId,
chartRevisionLog.config,
chartRevisionLog.createdAt,
chartRevisionLog.updatedAt,
]
)
// Remove any old dimensions and store the new ones
// We only note that a relationship exists between the chart and variable in the database; the actual dimension configuration is left to the json
await db.knexRaw(knex, `DELETE FROM chart_dimensions WHERE chartId=?`, [
chartId,
])
const newDimensions = fullConfig.dimensions ?? []
for (const [i, dim] of newDimensions.entries()) {
await db.knexRaw(
knex,
`INSERT INTO chart_dimensions (chartId, variableId, property, \`order\`) VALUES (?, ?, ?, ?)`,
[chartId, dim.variableId, dim.property, i]
)
}
// So we can generate country profiles including this chart data
if (fullConfig.isPublished && referencedVariablesMightChange)
// TODO: remove this ad hoc knex transaction context when we switch the function to knex
await denormalizeLatestCountryData(
knex,
newDimensions.map((d) => d.variableId)
)
if (fullConfig.isPublished) {
await retrieveChartConfigFromDbAndSaveToR2(knex, chartConfigId, {
directory: R2GrapherConfigDirectory.publishedGrapherBySlug,
filename: `${fullConfig.slug}.json`,
})
}
if (
fullConfig.isPublished &&
(!existingConfig || !existingConfig.isPublished)
) {
// Newly published, set publication info
await db.knexRaw(
knex,
`UPDATE charts SET publishedAt=?, publishedByUserId=? WHERE id = ? `,
[new Date(), user.id, chartId]
)
await triggerStaticBuild(user, `Publishing chart ${fullConfig.slug}`)
} else if (
!fullConfig.isPublished &&
existingConfig &&
existingConfig.isPublished
) {
// Unpublishing chart, delete any existing redirects to it
await db.knexRaw(
knex,
`DELETE FROM chart_slug_redirects WHERE chart_id = ?`,
[existingConfig.id]
)
await deleteGrapherConfigFromR2(
R2GrapherConfigDirectory.publishedGrapherBySlug,
`${existingConfig.slug}.json`
)
await triggerStaticBuild(user, `Unpublishing chart ${fullConfig.slug}`)
} else if (fullConfig.isPublished)
await triggerStaticBuild(user, `Updating chart ${fullConfig.slug}`)
return {
chartId,
savedPatch: patchConfig,
}
}
async function updateGrapherConfigsInR2(
knex: db.KnexReadonlyTransaction,
updatedCharts: { chartConfigId: string; isPublished: boolean }[],
updatedMultiDimViews: { chartConfigId: string; isPublished: boolean }[]
) {
const idsToUpdate = [
...updatedCharts.filter(({ isPublished }) => isPublished),
...updatedMultiDimViews,
].map(({ chartConfigId }) => chartConfigId)
const builder = knex<DbRawChartConfig>(ChartConfigsTableName)
.select("id", "full", "fullMd5")
.whereIn("id", idsToUpdate)
for await (const { id, full, fullMd5 } of builder.stream()) {
await saveGrapherConfigToR2ByUUID(id, full, fullMd5)
}
}
getRouteWithROTransaction(apiRouter, "/charts.json", async (req, res, trx) => {
const limit = parseIntOrUndefined(req.query.limit as string) ?? 10000
const charts = await db.knexRaw<OldChartFieldList>(
trx,
`-- sql
SELECT ${oldChartFieldList},
round(views_365d / 365, 1) as pageviewsPerDay
FROM charts
JOIN chart_configs ON chart_configs.id = charts.configId
JOIN users lastEditedByUser ON lastEditedByUser.id = charts.lastEditedByUserId
LEFT JOIN analytics_pageviews on (analytics_pageviews.url = CONCAT("https://ourworldindata.org/grapher/", chart_configs.slug) AND chart_configs.full ->> '$.isPublished' = "true" )
LEFT JOIN users publishedByUser ON publishedByUser.id = charts.publishedByUserId
ORDER BY charts.lastEditedAt DESC LIMIT ?
`,
[limit]
)
await assignTagsForCharts(trx, charts)
return { charts }
})
getRouteWithROTransaction(apiRouter, "/charts.csv", async (req, res, trx) => {
const limit = parseIntOrUndefined(req.query.limit as string) ?? 10000
// note: this query is extended from OldChart.listFields.
const charts = await db.knexRaw(
trx,
`-- sql
SELECT
charts.id,
chart_configs.full->>"$.version" AS version,
CONCAT("${BAKED_BASE_URL}/grapher/", chart_configs.full->>"$.slug") AS url,
CONCAT("${ADMIN_BASE_URL}", "/admin/charts/", charts.id, "/edit") AS editUrl,
chart_configs.full->>"$.slug" AS slug,
chart_configs.full->>"$.title" AS title,
chart_configs.full->>"$.subtitle" AS subtitle,
chart_configs.full->>"$.sourceDesc" AS sourceDesc,
chart_configs.full->>"$.note" AS note,
chart_configs.chartType AS type,
chart_configs.full->>"$.internalNotes" AS internalNotes,
chart_configs.full->>"$.variantName" AS variantName,
chart_configs.full->>"$.isPublished" AS isPublished,
chart_configs.full->>"$.tab" AS tab,
chart_configs.chartType IS NOT NULL AS hasChartTab,
JSON_EXTRACT(chart_configs.full, "$.hasMapTab") = true AS hasMapTab,
chart_configs.full->>"$.originUrl" AS originUrl,
charts.lastEditedAt,
charts.lastEditedByUserId,
lastEditedByUser.fullName AS lastEditedBy,
charts.publishedAt,
charts.publishedByUserId,
publishedByUser.fullName AS publishedBy
FROM charts
JOIN chart_configs ON chart_configs.id = charts.configId
JOIN users lastEditedByUser ON lastEditedByUser.id = charts.lastEditedByUserId
LEFT JOIN users publishedByUser ON publishedByUser.id = charts.publishedByUserId
ORDER BY charts.lastEditedAt DESC
LIMIT ?
`,
[limit]
)
// note: retrieving references is VERY slow.
// await Promise.all(
// charts.map(async (chart: any) => {
// const references = await getReferencesByChartId(chart.id)
// chart.references = references.length
// ? references.map((ref) => ref.url)
// : ""
// })
// )
// await Chart.assignTagsForCharts(charts)
res.setHeader("Content-disposition", "attachment; filename=charts.csv")
res.setHeader("content-type", "text/csv")
const csv = Papa.unparse(charts)
return csv
})
getRouteWithROTransaction(
apiRouter,
"/charts/:chartId.config.json",
async (req, res, trx) => expectChartById(trx, req.params.chartId)
)
getRouteWithROTransaction(
apiRouter,
"/charts/:chartId.parent.json",
async (req, res, trx) => {
const chartId = expectInt(req.params.chartId)
const parent = await getParentByChartId(trx, chartId)
const isInheritanceEnabled = await isInheritanceEnabledForChart(
trx,
chartId
)
return omitUndefinedValues({
variableId: parent?.variableId,
config: parent?.config,
isActive: isInheritanceEnabled,
})
}
)
getRouteWithROTransaction(
apiRouter,
"/charts/:chartId.patchConfig.json",
async (req, res, trx) => {
const chartId = expectInt(req.params.chartId)
const config = await expectPatchConfigByChartId(trx, chartId)
return config
}
)
getRouteWithROTransaction(
apiRouter,
"/editorData/namespaces.json",
async (req, res, trx) => {
const rows = await db.knexRaw<{
name: string
description?: string
isArchived: boolean
}>(
trx,
`SELECT DISTINCT
namespace AS name,
namespaces.description AS description,
namespaces.isArchived AS isArchived
FROM active_datasets
JOIN namespaces ON namespaces.name = active_datasets.namespace`
)
return {
namespaces: lodash
.sortBy(rows, (row) => row.description)
.map((namespace) => ({
...namespace,
isArchived: !!namespace.isArchived,
})),
}
}
)
getRouteWithROTransaction(
apiRouter,
"/charts/:chartId.logs.json",
async (req, res, trx) => ({
logs: await getLogsByChartId(
trx,
parseInt(req.params.chartId as string)
),
})
)
getRouteWithROTransaction(
apiRouter,
"/charts/:chartId.references.json",
async (req, res, trx) => {
const references = {
references: await getReferencesByChartId(
parseInt(req.params.chartId as string),
trx
),
}
return references
}
)
getRouteWithROTransaction(
apiRouter,
"/charts/:chartId.redirects.json",
async (req, res, trx) => ({
redirects: await getRedirectsByChartId(
trx,
parseInt(req.params.chartId as string)
),
})
)
getRouteWithROTransaction(
apiRouter,
"/charts/:chartId.pageviews.json",
async (req, res, trx) => {
const slug = await getChartSlugById(
trx,
parseInt(req.params.chartId as string)
)
if (!slug) return {}
const pageviewsByUrl = await db.knexRawFirst(
trx,
`-- sql
SELECT *
FROM
analytics_pageviews
WHERE
url = ?`,
[`https://ourworldindata.org/grapher/${slug}`]
)
return {
pageviews: pageviewsByUrl ?? undefined,
}
}
)
getRouteWithROTransaction(
apiRouter,
"/editorData/variables.json",
async (req, res, trx) => {
const datasets = []
const rows = await db.knexRaw<
Pick<DbRawVariable, "name" | "id"> & {
datasetId: number
datasetName: string
datasetVersion: string
} & Pick<
DbPlainDataset,
"namespace" | "isPrivate" | "nonRedistributable"
>
>(
trx,
`-- sql
SELECT
v.name,
v.id,
d.id as datasetId,
d.name as datasetName,
d.version as datasetVersion,
d.namespace,
d.isPrivate,
d.nonRedistributable
FROM variables as v JOIN active_datasets as d ON v.datasetId = d.id
ORDER BY d.updatedAt DESC
`
)
let dataset:
| {
id: number
name: string
version: string
namespace: string
isPrivate: boolean
nonRedistributable: boolean
variables: { id: number; name: string }[]
}
| undefined
for (const row of rows) {
if (!dataset || row.datasetName !== dataset.name) {
if (dataset) datasets.push(dataset)
dataset = {
id: row.datasetId,
name: row.datasetName,
version: row.datasetVersion,
namespace: row.namespace,
isPrivate: !!row.isPrivate,
nonRedistributable: !!row.nonRedistributable,
variables: [],
}
}
dataset.variables.push({
id: row.id,
name: row.name ?? "",
})
}
if (dataset) datasets.push(dataset)
return { datasets: datasets }
}
)
apiRouter.get("/data/variables/data/:variableStr.json", async (req, res) => {
const variableStr = req.params.variableStr as string
if (!variableStr) throw new JsonError("No variable id given")
if (variableStr.includes("+"))