首页 > 解决方案 > Naming convention recommendation for using mysql in nodejs

问题描述

please give me your guidance.

I'm using node with mysql database (without using orm).

i use snake_case naming convention for mysql.

my question is:

in node, should i use snake_case or use camelCase ?

for e.g. at models/movie.js:

snake_case:

return db.execute(SELECT title, daily_rental_rate FROM movies);

the result sent to the client:

{
title: 'abc',
daily_rental_rate: 20
}

camel_case:

return db.execute(SELECT title, daily_rental_rate as dailyRentalRate FROM movies);

the result sent to the client:

{
title: 'abc',
dailyRentalRate: 20
}

thank you so much /\

标签: mysqlnode.jsapinaming-conventionsbackend

解决方案


There is no fixed convention for JSON casing, however most APIs tend to use camelCase for properties, include Google, see their style guide here.

You can also map object properties within JavaScript, you don't have to do this manually in your queries. This allows you to be relatively flexible with your casing, even changing to kebab-case or snake_case if you wish to later on. This example uses the lodash library to convert object case.

const _ = require("lodash");

function objectToCamelCase(obj) {
    return _.mapKeys(obj, (v, k) => _.camelCase(k))
}

let rows = db.execute("SELECT title, daily_rental_rate FROM movies");
console.log("Result (snake_case): ", rows);
rows = rows.map(objectToCamelCase);
console.log("Result (camelCase):", rows);

The results might look like so:

Result (snake_case):

[
    {
        "title": "The Shawshank Redemption",
        "daily_rental_rate": "€2.99"
    },
    {
        "title": "Ferris Bueller's Day Off",
        "daily_rental_rate": "€2.99"
    }
]

Result (camelCase):

[
    {
        "title": "The Shawshank Redemption",
        "dailyRentalRate": "€2.99"
    },
    {
        "title": "Ferris Bueller's Day Off",
        "dailyRentalRate": "€2.99"
    }
]

推荐阅读