surrealdb-core 3.3.1

A scalable, distributed, collaborative, document-graph database, for the realtime web
use anyhow::Result;
use reblessive::tree::Stk;

use crate::catalog::Error;
use crate::catalog::providers::ApiProvider;
use crate::ctx::FrozenContext;
use crate::dbs::Options;
use crate::doc::CursorDoc;
use crate::expr::Base;
use crate::expr::statements::remove::api::RemoveApiStatement;
use crate::iam::{Action, ResourceKind};
use crate::key::schema::ApiKey;
use crate::legacy::expr_to_ident;
use crate::val::Value;

/// Process this type returning a computed simple Value
pub(crate) async fn remove_api_statement_compute(
	this: &RemoveApiStatement,
	stk: &mut Stk,
	ctx: &FrozenContext,
	opt: &Options,
	doc: Option<&CursorDoc>,
) -> Result<Value> {
	// Allowed to run?
	ctx.is_allowed(opt, Action::Edit, ResourceKind::Api, Base::Db)?;
	// Compute the name
	let name = expr_to_ident(stk, ctx, opt, doc, &this.name, "api name").await?;
	// Get the transaction
	let txn = ctx.tx();
	// Get the definition
	let (ns, db) = ctx.expect_ns_db_ids(opt).await?;
	// Check if the api exists
	let Some(ap) = txn.get_db_api(ns, db, &name, None).await? else {
		if this.if_exists {
			return Ok(Value::None);
		} else {
			return Err(Error::ApNotFound {
				value: name,
			}
			.into());
		}
	};

	// Delete the definition
	let name = ap.path.to_string();
	let key = ApiKey {
		ns,
		db,
		ap: std::borrow::Cow::Borrowed(&name),
	};
	txn.del_key(&key).await?;
	// Clear the cache
	txn.clear_cache();
	// Ok all good
	Ok(Value::None)
}