From e558704a8e7295c6e420ecce915699e2d4e40ab3 Mon Sep 17 00:00:00 2001 From: Pierce Thompson Date: Sun, 7 May 2023 04:35:01 -0400 Subject: [PATCH] Lazy initialize selectors --- src/lyrics.rs | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/lyrics.rs b/src/lyrics.rs index 380cb59..acb5a90 100644 --- a/src/lyrics.rs +++ b/src/lyrics.rs @@ -1,6 +1,7 @@ use actix_web::{get, web, Responder, Result}; use askama::Template; use futures::future; +use once_cell::sync::Lazy; use scraper::{Html, Selector}; use serde::Deserialize; @@ -9,6 +10,11 @@ use crate::genius::{self, GeniusApi}; use crate::templates::template; use crate::utils; +static SONG_ID_SELECTOR: Lazy = + Lazy::new(|| Selector::parse("meta[property='twitter:app:url:iphone']").unwrap()); +static LYRIC_SELECTOR: Lazy = + Lazy::new(|| Selector::parse("div[data-lyrics-container=true]").unwrap()); + struct Verse { title: String, lyrics: Vec, @@ -60,9 +66,8 @@ pub async fn lyrics(info: web::Query) -> Result { } fn get_song_id(document: &Html) -> crate::Result { - let parser = &Selector::parse("meta[property='twitter:app:url:iphone']").unwrap(); let meta = document - .select(parser) + .select(&SONG_ID_SELECTOR) .next() .ok_or("Failed to find meta tag with song ID")?; let id = meta @@ -75,9 +80,7 @@ fn get_song_id(document: &Html) -> crate::Result { } fn scrape_lyrics(document: &Html) -> Vec { - let parser = &Selector::parse("div[data-lyrics-container=true]").unwrap(); - - let text_iter = document.select(parser).flat_map(|x| x.text()); + let text_iter = document.select(&LYRIC_SELECTOR).flat_map(|x| x.text()); let mut verses = Vec::with_capacity(text_iter.size_hint().0);