If you’re building a , most likely you want to use names for all the fields in your GraphQL schema as recommended by the . But, it’s likely that your database is using a different convention. For example, in case with PostgreSQL, the practical naming convention to use is (feel free to ask why in the comments bellow). Let’s see a couple of solutions to this problem. GraphQL data API lowerCamelCase GraphQL specification snake_case Solution 1 You can use an ORM tool for such as Sequelize, Bookshelf, Objection.js, or another. Most of them are capable of converting field names to another case. But, that solution sounds boring, let’s just skip it :) Node.js Solution 2 Convert fields to at a GraphQL level inside types’ methods. Here is an example: snake_case camelCase resolve() This approach is quite verbose, but at least there is no “magic”, everything looks clear and straightforward. The down side is that you will end-up using mixed case in your data access code. Solution 3 Let’s see how to handle that sort of conversion automatically with , which is a very popular universal database client for Node.js. Knex.js Typically, you would start by creating file exporting a singleton instance of the Knex client: db.js So, you could use it in your data models like so ( ): models/User.js Executing method would generate the following SQL query: User.find() SELECT "id", "email", "is_admin" FROM "users" …and, would resolve to an array of objects with a bunch of snake_case fields (ouch!). This is very easy to fix by tweaking the list of field (column) names in your data model class(es) (see line #3): Now the SQL query generated by the method would change into: .find() SELECT "id", "email", "is_admin" as "isAdmin" FROM "users" Executing that method would return an array of perfectly shaped objects. What’s more interesting, is how to make sure that you can use camelCase properties with and inputs? Luckily, it should also be easy to tweak by overriding Knex’s and methods: JavaScript .where() .update() wrapdIdentifier(value) wrapsAsIdentifier(value) That’s it! Now you can do things like , , etc. User.find({ isAdmin: true }) User.update({ firstName: 'Bill' }).where({ id: 123 }) , if you want to play with GraphQL, PostgreSQL and Knex, the easiest way to start is by installing , the latest version of , and then running — this will create the initial project structure including all the core building blocks and dev tools in place. Happy coding! BTW Docker Yarn **yarn create data-api**
Share Your Thoughts