Skip to content

Commit

Permalink
feat: parse CAPI & DCR responses
Browse files Browse the repository at this point in the history
  • Loading branch information
mxdvl committed Feb 7, 2024
1 parent 8329898 commit 03e9b8c
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 21 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"sass": "1.57.1",
"svelte": "4.2.8",
"typescript": "5.1.6",
"valibot": "^0.28.1",
"vite": "5.0.12",
"web-vitals": "3.5.0"
},
Expand Down
9 changes: 9 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

78 changes: 57 additions & 21 deletions src/components/BlogFeed.astro
Original file line number Diff line number Diff line change
@@ -1,35 +1,43 @@
---
import {
parse,
object,
string,
number,
literal,
array,
picklist,
} from "valibot";
import { timeAgo } from "@guardian/libs";
const CAPI_KEY = import.meta.env.CAPI_KEY ?? "test";
type SeriesResult = {
id: string;
type: string;
sectionId: string;
sectionName: string;
webPublicationDate: string;
webTitle: string;
webUrl: string;
apiUrl: string;
isHosted: boolean;
pillarId: string;
pillarName: string;
fields: {
byline: string;
};
};
const searchResponseSchema = object({
response: object({
status: literal("ok"),
results: array(
object({
webUrl: string(),
webPublicationDate: string(),
webTitle: string(),
fields: object({
byline: string(),
}),
})
),
}),
});
const queryParams = new URLSearchParams({
tag: "info/series/engineering-blog",
"show-fields": "byline",
"api-key": CAPI_KEY,
});
const posts: SeriesResult[] = await fetch(
const posts = await fetch(
`https://content.guardianapis.com/search?${queryParams.toString()}`
)
.then((r) => r.json())
.then((d) => d.response.results);
.then((d) => parse(searchResponseSchema, d).response.results);
/**
* It would be good to use https://raw.githubusercontent.com/guardian/dotcom-rendering/main/dotcom-rendering/src/model/json-schema.json
Expand All @@ -50,6 +58,34 @@ type ArticleResult = {
}>;
}>;
};
const contentResultSchema = object({
mainMediaElements: array(
object({
data: object({
alt: string(),
}),
imageSources: array(
object({
weighting: picklist([
"inline",
"thumbnail",
"showcase",
"immersive",
"supporting",
"halfwidth",
]),
srcSet: array(
object({
src: string(),
width: number(),
})
),
})
),
})
),
});
---

<h3>Latest Engineering blog posts</h3>
Expand All @@ -59,9 +95,9 @@ type ArticleResult = {
const time = new Date(post.webPublicationDate).getTime();
const pubDate = timeAgo(time);

const article: ArticleResult = await fetch(
post.webUrl + ".json?dcr"
).then((r) => r.json());
const article = await fetch(post.webUrl + ".json?dcr")
.then((r) => r.json())
.then((d) => parse(contentResultSchema, d));

const media = article.mainMediaElements[0];

Expand Down

0 comments on commit 03e9b8c

Please sign in to comment.