use crate::Error;
use rusqlite::{Connection, params};
use serde_json::Value;
use std::fs;
pub trait Serializer {
fn serialize(&self, data: &Value) -> Result<Vec<u8>, Error>;
fn extension(&self) -> &str;
}
pub struct JSONSerializer {
pub minify: bool,
}
impl Serializer for JSONSerializer {
fn serialize(&self, d: &Value) -> Result<Vec<u8>, Error> {
if self.minify {
serde_json::to_vec(d).map_err(|e| e.into())
} else {
serde_json::to_vec_pretty(d).map_err(|e| e.into())
}
}
fn extension(&self) -> &str {
"json"
}
}
pub struct TypescriptSerializer {
pub minify: bool,
}
impl Serializer for TypescriptSerializer {
fn serialize(&self, d: &Value) -> Result<Vec<u8>, Error> {
let json = if self.minify {
serde_json::to_string(d)?
} else {
serde_json::to_string_pretty(d)?
};
Ok(format!("export const data = {};", json).into_bytes())
}
fn extension(&self) -> &str {
"ts"
}
}
pub struct SqliteSerializer;
impl Serializer for SqliteSerializer {
fn serialize(&self, d: &Value) -> Result<Vec<u8>, Error> {
let tmp = tempfile::NamedTempFile::new()?;
let conn = Connection::open(tmp.path())?;
self.populate_db(&conn, d)?;
fs::read(tmp.path()).map_err(|e| e.into())
}
fn extension(&self) -> &str {
"db"
}
}
impl SqliteSerializer {
fn populate_db(&self, conn: &Connection, d: &Value) -> Result<(), Error> {
conn.execute("CREATE TABLE data (id INTEGER PRIMARY KEY, value TEXT)", [])?;
if let Some(arr) = d.as_array() {
for (i, val) in arr.iter().enumerate() {
conn.execute(
"INSERT INTO data (id, value) VALUES (?1, ?2)",
params![i as i64, val.to_string()],
)?;
}
}
Ok(())
}
}