Skip to content

Commit ae851e3

Browse files
committed
Introduce minify_query
Useful to reduce the size of payload
1 parent 64fb5af commit ae851e3

File tree

4 files changed

+36
-2
lines changed

4 files changed

+36
-2
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,5 +105,6 @@ pub mod schema;
105105

106106
pub use crate::query::parse_query;
107107
pub use crate::schema::parse_schema;
108+
pub use crate::query::minify_query;
108109
pub use crate::position::Pos;
109110
pub use crate::format::Style;

src/query/error.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ pub type InternalError<'a> = Errors<Token<'a>, Token<'a>, Pos>;
1313
/// way to improve both error message and API.
1414
#[derive(Error, Debug)]
1515
#[error("query parse error: {}", _0)]
16-
pub struct ParseError(String);
16+
pub struct ParseError(pub (crate) String);
1717

1818
impl<'a> From<InternalError<'a>> for ParseError {
1919
fn from(e: InternalError<'a>) -> ParseError {

src/query/minify.rs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
use crate::tokenizer::{Kind, Token, TokenStream};
2+
use super::ParseError;
3+
use combine::Positioned;
4+
use combine::StreamOnce;
5+
6+
pub fn minify_query(source: String) -> Result<String, ParseError> {
7+
let mut bits: Vec<&str> = Vec::new();
8+
let mut stream = TokenStream::new(source.as_str());
9+
let mut prev_was_punctuator = false;
10+
11+
loop {
12+
match stream.uncons() {
13+
Ok(x) => {
14+
let token: Token = x;
15+
let is_non_punctuator = token.kind != Kind::Punctuator;
16+
17+
if prev_was_punctuator {
18+
if is_non_punctuator {
19+
bits.push(" ");
20+
}
21+
}
22+
23+
bits.push(token.value);
24+
prev_was_punctuator = is_non_punctuator;
25+
}
26+
Err(ref e) if e == &combine::easy::Error::end_of_input() => break,
27+
Err(e) => return Err(ParseError(format!("{} at {}", e, stream.position()))),
28+
}
29+
}
30+
31+
Ok(bits.join(""))
32+
}

src/query/mod.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,9 @@ mod ast;
44
mod error;
55
mod format;
66
mod grammar;
7-
7+
mod minify;
88

99
pub use self::grammar::{parse_query, consume_definition};
1010
pub use self::error::ParseError;
1111
pub use self::ast::*;
12+
pub use self::minify::minify_query;

0 commit comments

Comments
 (0)