slonik-interceptor-field-name-transformation
v48.8.7
Published
Transforms Slonik query result field names.
Downloads
46,996
Readme
slonik-interceptor-field-name-transformation
Transforms Slonik query result field names into camelCase.
Motivation
This interceptor removes the necessity to alias field names, e.g.
connection.any(sql`
SELECT
id,
full_name "fullName"
FROM person
`);Field name transformation uses the afterQuery interceptor method to format field names.
Installation
npm install slonik-interceptor-field-name-transformationConfiguration
You can configure which fields should be transformed by providing a test function to createFieldNameTransformationInterceptor
/**
* @property test Tests whether the field should be formatted.
* All fields that pass this test will have their names converted to camelCase.
*/
type ConfigurationType = {
test: (field: FieldType) => boolean;
};
(configuration: ConfigurationType) => InterceptorType;Example usage
import {
createPool
} from 'slonik';
import {
createFieldNameTransformationInterceptor
} from 'slonik-interceptor-field-name-transformation';
const interceptors = [
createFieldNameTransformationInterceptor({
test: (field) => {
return field.name !== '__typename' && /^[\d_a-z]+$/u.test(field.name);
},
})
];
const connection = createPool('postgres://', {
interceptors
});
connection.any(sql`
SELECT
id,
full_name,
__typename
FROM person
`);
// [
// {
// id: 1,
// fullName: 'John Doe',
// __typename: 'person'
// }
// ]