Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Knex/MySQL snake_case to camelCase, typecasting tinyint to boolean #3516

markuslerner started this conversation in Ideas
Discussion options

I was struggling for a long time to find a way to automatically convert snake_case MySQL database fields to camelCase and typecasting tinyint to boolean.

I finally found this solution, which works very well for me. I thought this might be useful to be included in the docs. I guess, it's quite a common case, but unfortunately I didn't find anything there yet. What you do you'll think?

Here's my custom src/mysql.ts:

// For more information about this file see https://dove.feathersjs.com/guides/cli/databases.html
import knex from 'knex'
import type { Knex } from 'knex'
import type { Application } from './declarations'
import { knexSnakeCaseMappers } from 'objection'
declare module './declarations' {
 interface Configuration {
 mysqlClient: Knex
 }
}
const typeCast = (field: any, next: any) => {
 if (field.type == 'TINY' && field.length == 1) {
 // Convert tinyint to boolean
 return field.string() === '1' // 1 = true, 0 = false
 }
 return next()
}
export const mysql = (app: Application) => {
 const config = app.get('mysql')
 const db = knex({
 ...config!,
 ...knexSnakeCaseMappers(),
 connection: {
 ...(config!.connection as {
 host?: string
 port?: number
 user?: string
 password?: string
 database?: string
 }),
 typeCast
 }
 })
 app.set('mysqlClient', db)
}
You must be logged in to vote

Replies: 1 comment

Comment options

I had similar issue. Thanks, you saved me a lot of time.
Here is my setting for PostgreSql and javascript.

// postgresql.js
import knex from "knex";
import { knexSnakeCaseMappers } from "objection";
export const postgresql = (app) => {
 const config = app.get("postgresql");
 const db = knex({ ...config, ...knexSnakeCaseMappers() });
 app.set("postgresqlClient", db);
};
You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Ideas
Labels
None yet

AltStyle によって変換されたページ (->オリジナル) /