Skip to content

Instantly share code, notes, and snippets.

@makvoid
Created Aug 25, 2022
Embed
What would you like to do?
"How to use Algolia as a game engine debugging tool in Rust" Example #1
use serde::{Deserialize, Serialize, Serializer};
use urlencoding;
fn main() -> Result<(), Box<dyn std::error::Error>> {
#[derive(Serialize, Debug)]
struct Float3 {
#[serde(rename="objectID")]
object_id: String,
x: f32,
y: f32,
z: f32,
}
// The credentials data
const APP_ID: &str = "";
const INDEX_NAME: &str = "";
const API_KEY: &str = "";
const ALGOLIA_AGENT: &str = "Algolia DataSender for Rust Dev (0.0.1)";
// let data = ....
// build the URI for the batch
let host = format!("{}.algolia.net", APP_ID.to_lowercase());
let path = format!("/1/indexes/{}/batch", urlencoding::encode(INDEX_NAME));
let uri = format!("https://{}{}", host, path);
let uri_with_client = format!("{}?x-algolia-agent={}", uri, ALGOLIA_AGENT);
// RECREATE THE REQUESTS STRUCTURE
// -------------------------------
// {"requests":[{"action":"updateObject","body":{"objectID":1,"name":"test_record"}}]}
// convert a pre-serialized JSON object into a request object for a batch request
fn build_batch_request_entry(data: &String) -> String {
format!("{{\"action\":\"updateObject\",\"body\":{}}}", data)
}
// wrap the individual requests into a batch
fn wrap_batch_request_entry(rows: &Vec<String>) -> String {
format!("{{\"requests\":[{}]}}", rows.join(","))
}
let raw_data = vec![
serde_json::to_string(&Float3 {
object_id: String::from("p1"),
x: 0.1,
y: 0.2,
z: 0.3,
})
.unwrap(),
serde_json::to_string(&Float3 {
object_id: String::from("p2"),
x: 1.1,
y: 1.2,
z: 1.3,
})
.unwrap(),
];
let data = wrap_batch_request_entry(&raw_data.iter().map(build_batch_request_entry).collect());
let client = reqwest::blocking::Client::new();
println!("REQUEST: {} {}", uri_with_client, data);
let res = client
.post(uri_with_client)
.header("x-algolia-api-key", API_KEY)
.header("x-algolia-application-id", APP_ID)
.body(data)
.send()?;
println!("RESPONSE: {:#?}", res);
println!("BODY: {}", res.text()?);
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment