@htc-class/simple-mysql
v1.0.4
Published
Simple MySQL Typescript wrapper, for learning/demonstration only
Downloads
1
Readme
@htc-class/simple-mysql
A very simple Typescript wrapper around
mysql2/promise
for demonstration, learning, and rudimentary applications.
Installation
$ npm install @htc-class/simple-mysql
Usage
import SimpleMySQL from '@htc-class/simple-mysql';
const db = new SimpleMySQL({
database: `pets`,
user: `jared`,
password: `goatbanjorodeo`,
});
// for selecting, use the `query()` method:
const selectResult = await db.query(`SELECT * FROM pets`);
// for updating, altering, droping, inserting, use `mutate()`
const dropResult = await db.mutate(`DROP TABLE pets`);
TypeScript Notes:
Both query()
and mutate()
returns a promise of a type called Result<T>
which
models the possibility of a successful statement, or an error, the type is this:
type Result<T> =
| {
ok: true;
value: T;
}
| {
ok: false;
error: string;
};
The query()
method is generic, allowing you to pass a type that you will get back an
array of if there is no error. But please note, the type is not validated at runtime
in any way, so make sure it is correct!
query()
returns a promise of a result which returns an array of the generic type you
provide. The TypeScript signature of query()
is:
function query<RowType = unknown>(query: string): Promise<Result<RowType[]>>;
That means if your users
table had 3 columns, an id = INT
, name = TEXT
, and
is_admin = BOOL
, you could express that in TypeScript like so:
type UserRow = {
id: number;
name: string;
is_admin: boolean;
};
const result = await db.query<UserRow>(`SELECT * FROM users`);
if (result.ok) {
console.log(result.value);
// result.value = UserRow[]
// > [{ id: 1, name: "Bob", is_admin: true}]
} else {
console.error(result.error);
}
The mutate()
method is a bit simpler, it just returns the type:
Promise<Result<{ affectedItems: number }>>
Which means you can use it like this:
const result = await db.mutate(`UPDATE users SET first_name = "Jared" WHERE id = 32;`);
if (result.ok) {
console.log(`Updated ${result.value.affectedItems} rows.`);
} else {
console.error(result.error);
}