0.0.1 • Published 4 years ago

@sqleton/mysql v0.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
4 years ago

CircleCI

SQLeton for MySQL

Install

To use this library, you will first need to install a mysql client library.

Here two of the most used libraries:

  • npm install mysql
  • npm install mysql2

Then install this library: npm install @sqleton/mysql --save

Usage

1. Create a pool or connection:

import mysql from 'mysql2';

const pool = mysql.createPool({
  //...
});

2. Create a query function:

const findPostsByQuery = (where: Query | undefined): TypedQuery<Post[]> => {
  const whereQuery = createWhere(where);

  return {
    query: `SELECT * as count FROM post ${whereQuery}`,
    params: whereQuery.params
  };
}

const findPostByIdQuery = (userId: string): TypedQuery<Post> => {
  return {
    query: `SELECT COUNT(*) as count FROM post p WHERE p.user_id = ?`,
    params: [userId],
    transform: rows => rows && rows[0]
  };
}

3. Bind query builders to execution method:

// Dynamic query: the conditions or other fields in query may vary
const useFindPostsBy = useQuery(findPostsByQuery)

// Prepared query: the query won't change depending on the parameters
const useFindPostById = usePreparedQuery(findPostByIdQuery)

4. Bind functions to a pool or connection.

const findPostsBy = useFindPostsBy(pool)
const findPostById = useFindPostsBy(pool)

Note: When using transactions, don't forget to rebind your functions with the given transaction connection.

5. Use the functions as you would normally

Examples

More examples are available under the samples folder.

Contributors

If you are interested and want to help out, don't hesitate to contact me or to create a pull request with your fixes / features.

  1. Clone the repository

  2. Install dependencies npm install

  3. Launch unit tests situated in ./tests. The unit tests are written in Jest. npm run test:unit

License

This project is licensed under the MIT License - see the LICENSE.md file for details