feat: more compact _id methods, url! macro

This commit is contained in:
əlemi 2024-03-20 09:42:25 +01:00
parent 178ad1b75d
commit dcaf5d5c2b
Signed by: alemi
GPG key ID: A4895B84D311642C
4 changed files with 29 additions and 12 deletions

View file

@ -5,7 +5,7 @@ use crate::{activitystream::Base, model::activity, server::Context};
pub async fn view(State(ctx) : State<Context>, Path(id): Path<String>) -> Result<Json<serde_json::Value>, StatusCode> { pub async fn view(State(ctx) : State<Context>, Path(id): Path<String>) -> Result<Json<serde_json::Value>, StatusCode> {
match activity::Entity::find_by_id(ctx.activity_uri(id)).one(ctx.db()).await { match activity::Entity::find_by_id(ctx.aid(id)).one(ctx.db()).await {
Ok(Some(activity)) => Ok(Json(activity.underlying_json_object())), Ok(Some(activity)) => Ok(Json(activity.underlying_json_object())),
Ok(None) => Err(StatusCode::NOT_FOUND), Ok(None) => Err(StatusCode::NOT_FOUND),
Err(e) => { Err(e) => {

View file

@ -5,7 +5,7 @@ use crate::{activitystream::Base, model::object, server::Context};
pub async fn view(State(ctx) : State<Context>, Path(id): Path<String>) -> Result<Json<serde_json::Value>, StatusCode> { pub async fn view(State(ctx) : State<Context>, Path(id): Path<String>) -> Result<Json<serde_json::Value>, StatusCode> {
match object::Entity::find_by_id(ctx.object_uri(id)).one(ctx.db()).await { match object::Entity::find_by_id(ctx.oid(id)).one(ctx.db()).await {
Ok(Some(object)) => Ok(Json(object.underlying_json_object())), Ok(Some(object)) => Ok(Json(object.underlying_json_object())),
Ok(None) => Err(StatusCode::NOT_FOUND), Ok(None) => Err(StatusCode::NOT_FOUND),
Err(e) => { Err(e) => {

View file

@ -3,14 +3,14 @@ use std::sync::Arc;
use axum::{extract::{Path, Query, State}, http::StatusCode, Json}; use axum::{extract::{Path, Query, State}, http::StatusCode, Json};
use sea_orm::{ColumnTrait, Condition, DatabaseConnection, EntityTrait, IntoActiveModel, Order, QueryFilter, QueryOrder, QuerySelect}; use sea_orm::{ColumnTrait, Condition, DatabaseConnection, EntityTrait, IntoActiveModel, Order, QueryFilter, QueryOrder, QuerySelect};
use crate::{activitystream::{self, object::{activity::{Activity, ActivityType}, collection::{page::CollectionPageMut, CollectionMut, CollectionType}, ObjectType}, Base, BaseMut, BaseType, Node}, model::{self, activity, object, user}, server::Context}; use crate::{activitystream::{self, object::{activity::{Activity, ActivityType}, collection::{page::CollectionPageMut, CollectionMut, CollectionType}, ObjectType}, Base, BaseMut, BaseType, Node}, model::{self, activity, object, user}, server::Context, url};
pub async fn list(State(_db) : State<Arc<DatabaseConnection>>) -> Result<Json<serde_json::Value>, StatusCode> { pub async fn list(State(_db) : State<Arc<DatabaseConnection>>) -> Result<Json<serde_json::Value>, StatusCode> {
todo!() todo!()
} }
pub async fn view(State(ctx) : State<Context>, Path(id): Path<String>) -> Result<Json<serde_json::Value>, StatusCode> { pub async fn view(State(ctx) : State<Context>, Path(id): Path<String>) -> Result<Json<serde_json::Value>, StatusCode> {
match user::Entity::find_by_id(ctx.user_uri(id)).one(ctx.db()).await { match user::Entity::find_by_id(ctx.uid(id)).one(ctx.db()).await {
Ok(Some(user)) => Ok(Json(user.underlying_json_object())), Ok(Some(user)) => Ok(Json(user.underlying_json_object())),
Ok(None) => Err(StatusCode::NOT_FOUND), Ok(None) => Err(StatusCode::NOT_FOUND),
Err(e) => { Err(e) => {
@ -29,7 +29,7 @@ pub async fn outbox(
// find requested recent post, to filter based on its date (use now() as fallback) // find requested recent post, to filter based on its date (use now() as fallback)
let before = if let Some(before) = page.max_id { let before = if let Some(before) = page.max_id {
match model::activity::Entity::find_by_id(ctx.activity_uri(before)) match model::activity::Entity::find_by_id(ctx.aid(before))
.one(ctx.db()).await .one(ctx.db()).await
{ {
Ok(None) => return Err(StatusCode::NOT_FOUND), Ok(None) => return Err(StatusCode::NOT_FOUND),
@ -58,8 +58,8 @@ pub async fn outbox(
obj obj
// TODO set id, calculate uri from given args // TODO set id, calculate uri from given args
.set_collection_type(Some(CollectionType::OrderedCollectionPage)) .set_collection_type(Some(CollectionType::OrderedCollectionPage))
.set_part_of(Node::link(&format!("http://localhost:3000/users/{id}/outbox"))) .set_part_of(Node::link(&url!(ctx, "/users/{id}/outbox")))
.set_next(Node::link(&format!("http://localhost:3000/users/{id}/outbox?page=true&max_id={next}"))) .set_next(Node::link(&url!(ctx, "/users/{id}/outbox?page=true&max_id={next}")))
.set_ordered_items(Node::array(items)); .set_ordered_items(Node::array(items));
Ok(Json(obj)) Ok(Json(obj))
}, },
@ -68,9 +68,9 @@ pub async fn outbox(
} else { } else {
let mut obj = crate::activitystream::object(); let mut obj = crate::activitystream::object();
obj obj
.set_id(Some(&format!("http://localhost:3000/users/{id}/outbox"))) .set_id(Some(&url!(ctx, "/users/{id}/outbox")))
.set_collection_type(Some(CollectionType::OrderedCollection)) .set_collection_type(Some(CollectionType::OrderedCollection))
.set_first(Node::link(&format!("http://localhost:3000/users/{id}/outbox?page=true"))); .set_first(Node::link(&url!(ctx, "/users/{id}/outbox?page=true")));
Ok(Json(obj.underlying_json_object())) Ok(Json(obj.underlying_json_object()))
} }
} }

View file

@ -11,6 +11,13 @@ struct ContextInner {
domain: String, domain: String,
} }
#[macro_export]
macro_rules! url {
($ctx:expr, $($args: tt)*) => {
format!("{}{}", $ctx.base(), format!($($args)*))
};
}
impl Context { impl Context {
pub fn new(db: DatabaseConnection, mut domain: String) -> Self { pub fn new(db: DatabaseConnection, mut domain: String) -> Self {
if !domain.starts_with("http") { if !domain.starts_with("http") {
@ -26,24 +33,34 @@ impl Context {
&self.0.db &self.0.db
} }
pub fn base(&self) -> &str {
&self.0.domain
}
pub fn uri(&self, entity: &str, id: String) -> String { pub fn uri(&self, entity: &str, id: String) -> String {
if id.starts_with("http") { id } else { if id.starts_with("http") { id } else {
format!("{}/{}/{}", self.0.domain, entity, id) format!("{}/{}/{}", self.0.domain, entity, id)
} }
} }
pub fn user_uri(&self, id: String) -> String { // TODO maybe redo these with enums? idk
/// get full user id uri
pub fn uid(&self, id: String) -> String {
self.uri("users", id) self.uri("users", id)
} }
pub fn object_uri(&self, id: String) -> String { /// get full object id uri
pub fn oid(&self, id: String) -> String {
self.uri("objects", id) self.uri("objects", id)
} }
pub fn activity_uri(&self, id: String) -> String { /// get full activity id uri
pub fn aid(&self, id: String) -> String {
self.uri("activities", id) self.uri("activities", id)
} }
/// get bare uri, usually an uuid but unspecified
pub fn id(&self, id: String) -> String { pub fn id(&self, id: String) -> String {
if id.starts_with(&self.0.domain) { if id.starts_with(&self.0.domain) {
let mut out = id.replace(&self.0.domain, ""); let mut out = id.replace(&self.0.domain, "");