У меня есть такой код:
Express:
// file: '/src/index.ts'
import express, { Application } from "express";
import UserRoutes from "./routes"
const PORT = 3000;
const app: Application = express()
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use('/api/', UserRoutes)
app.listen(PORT, () => console.log('Server started'))
Инициализация node-postgres: [UPDATED]
// file: '/src/db.ts'
import {
Pool,
type PoolClient,
type QueryResult,
type QueryResultRow
} from 'pg';
const pool = new Pool();
export type DatabaseType = {
query: (text: string, params?: unknown[]) => Promise<QueryResult<QueryResultRow>>;
getClient: () => Promise<PoolClient>;
}
const db: DatabaseType = {
query: (text, params) => pool.query(text, params),
getClient: () => pool.connect()
};
export default db;
Services:
// file: '/src/services.ts'
import db from './db'
export default {
getAllUsers: function getAllUsers() {
return db
.query('SELECT * FROM users ORDER BY user_id ASC')
.then((result) => result.rows)
.catch((error) => error);
},
getUserById: function getUserById(userId) {
return db
.query('SELECT * FROM users WHERE user_id = $1', [userId])
.then((result) => result.rows)
.catch((error) => error);
},
updateUser: function updateUser(username, email, userId) {
return db
.query(`
UPDATE users
SET username = $1, email = $2
WHERE user_id = $3
RETURNING *
`,
[username, email, userId]
)
.then((result) => result.rows)
.catch((error) => error);
},
deleteUser: function deleteUser(userId) {
return db
.query('DELETE FROM users WHERE user_id = $1 RETURNING user_id', [userId])
.then((result) => result.rows)
.catch((error) => error);
},
createUser: function createUser(username, email) {
return db
.query(`
INSERT INTO users (username, email)
VALUES ($1, $2)
RETURNING *
`,
[username, email]
)
.then((result) => result.rows)
.catch((error) => error);
},
};
Routes: (не все)
// file: '/src/routes.ts'
import {
Request,
Response,
NextFunction,
Router
} from "express"
import usersServices from "./services";
async function getAllUsers(
req: Request,
res: Response,
next: NextFunction
) {
const result = await usersServices.getAllUsers();
if (result instanceof Error) {
return next(result);
}
res
.status(200)
.json({
data: result,
});
}
const routes = Router()
routes.get('/users/', getAllUsers);
export default routes
Помогите типизировать db, result, error
ps: здесь использую CJS модули, знаю что TS использует ESM.