Response object keys in snake_case #2050
mastermunj
started this conversation in
General
Replies: 2 comments 5 replies
-
You can make use of transformers, here is a package: https://github.com/kmorpex/adonis-bublebee-ts#readme |
Beta Was this translation helpful? Give feedback.
5 replies
-
Okay, so here's something I have been able to put together that seems to work. import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
import _ from 'lodash';
import { safeParse, safeStringify } from '@poppinss/utils';
export default class ResponseResponseCaseConverter {
public async handle({ params, request, response }: HttpContextContract, next: () => Promise<void>): Promise<void> {
request.updateBody(this.toCamelCase(request.all()));
request.updateQs(this.toCamelCase(params));
await next();
const body = response.lazyBody[0];
try {
if (typeof body === 'object') {
response.send(this.toSnakeCase(safeParse(safeStringify(body))));
}
} catch (error) {}
}
private toCamelCase(object: Record<string, unknown>): Record<string, unknown> {
const transformed = _.transform(object, (result: Record<string, unknown>, value, key: string) => {
result[_.camelCase(key)] = _.isObject(value) ? this.toCamelCase(value as Record<string, unknown>) : value;
});
return _.assign(object, transformed);
}
private toSnakeCase(object: Record<string, unknown>): Record<string, unknown> {
const transformed = _.transform(object, (result: Record<string, unknown>, value, key: string) => {
result[_.snakeCase(key)] = _.isObject(value) ? this.toSnakeCase(value as Record<string, unknown>) : value;
});
return _.assign(object, transformed);
}
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi,
I want to be able to ensure that all the keys in json response are always in snake_case. For most of the cases where the returned values are model(s), it gets serialized and the output is as expected.
In cases where a custom object is created based on certain logic, the returned output does not get serialize, making camelCase keys go in the output.
Possible solutions that come in my mind:
Please guide on another better approach if any.
Beta Was this translation helpful? Give feedback.
All reactions