Skip to content

Commit dae96dd

Browse files
authored
feat(filter): add JSON body rename transformations (#5)
See: Kong/kong#13131
1 parent b75616d commit dae96dd

File tree

2 files changed

+280
-64
lines changed

2 files changed

+280
-64
lines changed

src/filter.rs

Lines changed: 1 addition & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -184,8 +184,6 @@ impl ResponseTransformerHttp {
184184
}
185185

186186
fn transform_body(&self, tx: &Json, body: Vec<u8>) {
187-
let mut changed = false;
188-
189187
let mut json = match serde_json::from_slice(&body) {
190188
Ok(JsonValue::Object(value)) => value,
191189
Ok(other) => {
@@ -201,67 +199,7 @@ impl ResponseTransformerHttp {
201199
}
202200
};
203201

204-
tx.remove.iter().for_each(|field| {
205-
if json.remove(field).is_some() {
206-
info!("removed field {:?}", field);
207-
changed = true;
208-
}
209-
});
210-
211-
tx.replace.iter().for_each(|(field, value)| {
212-
if let Some(found) = json.get_mut(field) {
213-
info!("replacing field {:?} {:?} => {:?}", field, found, value);
214-
*found = value.clone();
215-
changed = true;
216-
}
217-
});
218-
219-
tx.add.iter().for_each(|(field, value)| {
220-
if !json.contains_key(field) {
221-
info!("adding field {:?} {:?}", field, value);
222-
json.insert(field.to_owned(), value.clone());
223-
changed = true;
224-
}
225-
});
226-
227-
tx.append.iter().for_each(|(field, value)| {
228-
json.entry(field)
229-
.and_modify(|found| {
230-
let current = found.take();
231-
let mut appended = false;
232-
233-
*found = match current {
234-
JsonValue::String(_) => {
235-
appended = true;
236-
serde_json::json!([current, value.clone()])
237-
}
238-
JsonValue::Array(mut arr) => {
239-
appended = true;
240-
arr.push(value.clone());
241-
arr.into()
242-
}
243-
// XXX: this branch is not fully compatible with the Lua plugin
244-
//
245-
// The lua plugin doesn't attempt to disambiguate between an
246-
// array-like table and a map-like table. It just blindly calls
247-
// the `table.insert()` function.
248-
_ => current,
249-
};
250-
251-
if appended {
252-
changed = true;
253-
info!("appended {:?} to {:?}", value, field);
254-
}
255-
})
256-
.or_insert_with(|| {
257-
changed = true;
258-
let new = serde_json::json!([value]);
259-
info!("inserted {:?} to {:?}", new, field);
260-
new
261-
});
262-
});
263-
264-
if !changed {
202+
if !tx.transform_body(&mut json) {
265203
info!("no response body changes were applied");
266204
return;
267205
}

0 commit comments

Comments
 (0)