Rust examples
Small programs built on the audiencekit crate. Each keeps its work in public functions, so the crate’s tests run
them against a fake API, and runs as a program:
AUDIENCEKIT_TOKEN=… AUDIENCEKIT_HOST=hotmess.social cargo run --example news_digest -- Denver| File | What it shows | Credential |
|---|---|---|
listings_page.rs |
A static page of the audience’s public listings, for a scheduled job to publish | A public:read service token |
news_digest.rs |
A Markdown digest of a locale’s news and its national news, for a newsletter | An application API key |
community.rs |
The whole community as JSON, or the public listings with --public |
An application API key (a service token with --public) |
graphql_documents.rs |
Writes every document the client sends, for the schema check | None |
listings_page.rs
Section titled “listings_page.rs”//! A static page of the audience's public listings, for a venue guide or a city site to publish on a schedule (a//! cron job, a CI workflow) rather than reading the API on every request.//!//! ```sh//! AUDIENCEKIT_TOKEN=akst_… cargo run --example listings_page > public/index.html//! ```//!//! The service token needs the `public:read` scope.
use audiencekit::{Client, PublicListing};
/// Text made safe to put in HTML.pub fn escape(text: &str) -> String { text.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """).replace('\'', "'")}
/// One listing as HTML: venues with their address, events with their time, posts with their text.pub fn render_listing(listing: &PublicListing) -> String { let title = escape(listing.title.as_deref().unwrap_or_default()); match listing.kind.as_str() { "venue" => format!("<h2>{title}</h2><p>{}</p>", escape(listing.address.as_deref().unwrap_or_default())), "event" => { let when = listing.start_at.map(|at| at.to_rfc3339()).unwrap_or_default(); let canceled = if listing.is_canceled == Some(true) { " <strong>Canceled</strong>" } else { "" }; let venue = escape(listing.venue_name.as_deref().unwrap_or_default()); format!("<h3>{title}</h3><p><time datetime=\"{when}\">{when}</time> at {venue}{canceled}</p>") } "post" => { format!( "<article><h3>{title}</h3><p>{}</p></article>", escape(listing.description.as_deref().unwrap_or_default()) ) } _ => String::new(), }}
/// The whole page. "Community" listings show in full only to members, so they're left out of a public page.pub async fn render_page(client: &Client) -> audiencekit::Result<String> { let listings = client.public_listings().await?; let body: Vec<String> = listings.iter().filter(|listing| listing.is_public()).map(render_listing).collect(); Ok(format!("<!doctype html><meta charset=\"utf-8\"><title>What's on</title>\n{}\n", body.join("\n")))}
#[allow(dead_code)]#[tokio::main]async fn main() -> Result<(), Box<dyn std::error::Error>> { print!("{}", render_page(&Client::from_env()?).await?); Ok(())}news_digest.rs
Section titled “news_digest.rs”//! A Markdown digest of a locale's news, for a newsletter or a Discord post.//!//! ```sh//! AUDIENCEKIT_TOKEN=<application API key> AUDIENCEKIT_HOST=hotmess.social cargo run --example news_digest -- Denver//! ```//!//! Prints nothing for an audience without Soapbox, rather than failing.
use audiencekit::{Article, ArticleQuery, Client};
/// One article as a Markdown list item. A teaser carries only the start: the rest is on the publication's site.pub fn line(article: &Article) -> String { let name = &article.publication.name; let mut text = format!("- **{}**, {} for {name}", article.title, article.byline); if let (true, Some(url)) = (article.teaser, &article.canonical_url) { text.push_str(&format!(" ([read on {name}](https://github.com/lwm-luminx/audience-kit-sdk/blob/main/rust/examples/{url}))")); } if let Some(summary) = &article.summary { text.push_str(&format!("\n {summary}")); } if let Some(disclosure) = &article.disclosure { text.push_str(&format!("\n _{disclosure}_")); } text}
/// The digest for the locale named `locale_name` (or the audience's first): its news, then the national news.pub async fn digest(client: &Client, locale_name: Option<&str>) -> audiencekit::Result<String> { let locales = client.locales().await?; let Some(locale) = locales.iter().find(|l| l.name.as_deref() == locale_name).or(locales.first()) else { return Ok(String::new()); }; let query = ArticleQuery { locale_id: Some(locale.id.clone()), first: Some(10), ..Default::default() }; let (local, national) = tokio::try_join!(client.articles(&query), client.national_articles(Some(&locale.id), Some(5)))?; let mut sections = vec![format!("# {} this week", locale.name.as_deref().unwrap_or("Your city"))]; if !local.is_empty() { sections.push(format!("## Local news\n\n{}", local.iter().map(line).collect::<Vec<_>>().join("\n"))); } let elsewhere: Vec<String> = national.iter().filter(|article| !local.iter().any(|seen| seen.id == article.id)).map(line).collect(); if !elsewhere.is_empty() { sections.push(format!("## Around the country\n\n{}", elsewhere.join("\n"))); } Ok(if sections.len() > 1 { format!("{}\n", sections.join("\n\n")) } else { String::new() })}
#[allow(dead_code)]#[tokio::main]async fn main() -> Result<(), Box<dyn std::error::Error>> { let client = Client::from_env()?; print!("{}", digest(&client, std::env::args().nth(1).as_deref()).await?); Ok(())}community.rs
Section titled “community.rs”//! Prints an audience's community (its audience, locales, venues, people, upcoming events and series) as JSON, the//! way goosed or any other agent host would read it in. Configured from the environment, as goose passes an//! extension its secrets://!//! ```sh//! AUDIENCEKIT_TOKEN=<application API key> AUDIENCEKIT_HOST=hotmess.social cargo run --example community > community.json//! ```//!//! With `--public`, prints the public listings instead (venues, events and posts as the audience's websites show//! them), which a `public:read` service token reads.
#[tokio::main]async fn main() -> Result<(), Box<dyn std::error::Error>> { let client = audiencekit::Client::from_env()?; let json = if std::env::args().any(|argument| argument == "--public") { serde_json::to_string_pretty(&client.public_listings().await?)? } else { serde_json::to_string_pretty(&client.community().await?)? }; println!("{json}"); Ok(())}graphql_documents.rs
Section titled “graphql_documents.rs”//! Writes every GraphQL document the typed calls can send, built for an audience with every module, to a directory//! as `<OperationName>.graphql`, so the repository's schema check (scripts/graphql/check.mjs) can validate them://!//! ```sh//! cargo run --example graphql_documents -- target/graphql//! ```
use std::{env, fs, path::PathBuf, process};
fn main() { let Some(directory) = env::args().nth(1).map(PathBuf::from) else { eprintln!("usage: cargo run --example graphql_documents -- <directory>"); process::exit(2); }; fs::create_dir_all(&directory).expect("create the directory"); let documents = audiencekit::operations::documents(); for (name, text) in &documents { fs::write(directory.join(format!("{name}.graphql")), format!("{text}\n")).expect("write a document"); } println!("Wrote {} documents to {}.", documents.len(), directory.display());}