Skip to content

Commit

Permalink
Merge pull request #8 from shopware/next-37316/add-trigger-indexing-c…
Browse files Browse the repository at this point in the history
…ommand

NEXT-37316 - add trigger indexing command
  • Loading branch information
LarsKemper authored Jul 29, 2024
2 parents 91d61b3 + 6bce91d commit 25efd7d
Show file tree
Hide file tree
Showing 4 changed files with 61 additions and 5 deletions.
27 changes: 27 additions & 0 deletions src/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ pub struct SwClient {
}

impl SwClient {
pub const DEFAULT_IN_FLIGHT: usize = 8;

pub async fn new(credentials: Credentials, in_flight_limit: usize) -> anyhow::Result<Self> {
let mut default_headers = HeaderMap::default();
// This header is needed, otherwise the response would be "application/vnd.api+json" (by default)
Expand Down Expand Up @@ -255,6 +257,26 @@ impl SwClient {
Ok(res)
}

pub async fn index(&self, skip: Vec<String>) -> anyhow::Result<()> {
let access_token = self.access_token.lock().unwrap().clone();

let response = self
.client
.post(format!("{}/api/_action/index", self.credentials.base_url))
.bearer_auth(access_token)
.json(&IndexBody { skip })
.send()
.await?;

if !response.status().is_success() {
let status = response.status();
let body: SwErrorBody = Self::deserialize(response).await?;
return Err(SwApiError::Server(status, body).into());
}

Ok(())
}

async fn deserialize<T>(response: Response) -> Result<T, SwApiError>
where
T: for<'a> Deserialize<'a> + Debug + Send + 'static,
Expand All @@ -281,6 +303,11 @@ impl SwClient {
}
}

#[derive(Debug, Serialize)]
struct IndexBody {
skip: Vec<String>,
}

#[derive(Debug, Serialize)]
struct AuthBody {
grant_type: String,
Expand Down
7 changes: 7 additions & 0 deletions src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,13 @@ pub struct Cli {

#[derive(Subcommand)]
pub enum Commands {
/// Trigger indexing of all registered indexer in shopware asynchronously.
Index {
// Array of indexer names to be skipped
#[arg(short, long)]
skip: Vec<String>,
},

/// Authenticate with a given shopware shop via integration admin API.
/// Credentials are stored in .credentials.toml in the current working directory.
Auth {
Expand Down
12 changes: 12 additions & 0 deletions src/config_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
//! Utilizes https://serde.rs/
use crate::api::filter::{CriteriaFilter, CriteriaSorting};
use anyhow::Context;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;

Expand All @@ -16,6 +17,17 @@ pub struct Credentials {
pub access_key_secret: String,
}

impl Credentials {
pub async fn read_credentials() -> anyhow::Result<Credentials> {
let serialized_credentials = tokio::fs::read_to_string("./.credentials.toml")
.await
.context("No .credentials.toml found. Call command auth first.")?;

let credentials: Credentials = toml::from_str(&serialized_credentials)?;
Ok(credentials)
}
}

#[derive(Debug, Deserialize)]
pub struct Schema {
pub entity: String,
Expand Down
20 changes: 15 additions & 5 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ async fn main() -> anyhow::Result<()> {
let cli = Cli::parse();

match cli.command {
Commands::Index { skip } => {
index(skip).await?;
println!("Successfully triggered indexing.");
}
Commands::Auth { domain, id, secret } => {
auth(domain, id, secret).await?;
println!("Successfully authenticated. You can continue with other commands now.")
Expand Down Expand Up @@ -71,6 +75,15 @@ async fn main() -> anyhow::Result<()> {
Ok(())
}

async fn index(skip: Vec<String>) -> anyhow::Result<()> {
let credentials = Credentials::read_credentials().await?;

let sw_client = SwClient::new(credentials, SwClient::DEFAULT_IN_FLIGHT).await?;
sw_client.index(skip).await?;

Ok(())
}

async fn auth(domain: String, id: String, secret: String) -> anyhow::Result<()> {
let credentials = Credentials {
base_url: domain.trim_end_matches('/').to_string(),
Expand All @@ -79,7 +92,7 @@ async fn auth(domain: String, id: String, secret: String) -> anyhow::Result<()>
};

// check if credentials work
let _ = SwClient::new(credentials.clone(), 8).await?;
let _ = SwClient::new(credentials.clone(), SwClient::DEFAULT_IN_FLIGHT).await?;

// write them to file
let serialized = toml::to_string(&credentials)?;
Expand Down Expand Up @@ -107,10 +120,7 @@ async fn create_context(
}
}

let serialized_credentials = tokio::fs::read_to_string("./.credentials.toml")
.await
.context("No .credentials.toml found. Call command auth first.")?;
let credentials: Credentials = toml::from_str(&serialized_credentials)?;
let credentials = Credentials::read_credentials().await?;
let sw_client = SwClient::new(credentials, in_flight_limit).await?;

let api_schema = sw_client.entity_schema().await;
Expand Down

0 comments on commit 25efd7d

Please sign in to comment.