I've created a TypeScript
class that looks like this:
class User {
static readAll(): Promise<IUser[]> {
return new Promise((resolve, reject) => {
connection.query<IUser[]>("SELECT * FROM users", (err , res) => {
if (err) reject(err)
else resolve(res)
})
})
}
static readById(user_id: number): Promise<IUser | undefined> {
return new Promise((resolve, reject) => {
connection.query<IUser[]>(
"SELECT * FROM users WHERE id = ?",
[user_id],
(err, res) => {
if (err) reject(err)
else resolve(res?.[0])
}
)
})
}
static create(req : Request) : Promise<IUser> {
return new Promise((resolve, reject) => {
connection.query<OkPacket>(
"INSERT INTO users (email, password, admin) VALUES(?,?,?)",
[req.body.email, req.body.password, req.body.admin],
(err, res) => {
if (err) reject(err)
else
this.readById(res.insertId)
.then(user => resolve(user!))
.catch(reject)
}
)
})
}
static update(user: IUser): Promise<IUser | undefined> {
return new Promise((resolve, reject) => {
connection.query<OkPacket>(
"UPDATE users SET email = ?, password = ?, admin = ? WHERE id = ?",
[user.email, user.password, user.admin, user.id],
(err, res) => {
if (err) reject(err)
else
this.readById(user.id!)
.then(resolve)
.catch(reject)
}
)
})
}
static remove(user_id: number): Promise<number> {
return new Promise((resolve, reject) => {
connection.query<OkPacket>(
"DELETE FROM users WHERE id = ?",
[user_id],
(err, res) => {
if (err) reject(err)
else resolve(res.affectedRows)
}
)
})
}
}
However, I'm struggling to import these methods into another file directly. I currently have to instantiate a User
object in order to access the methods like User.create()
. Is there a better way to export these methods so they can be easily imported and used in other files?
I'm uncertain how to properly export these methods so they can be imported seamlessly into another file.