index.js 853 B

123456789101112131415161718192021222324252627282930
  1. import { createPool } from 'mysql2/promise';
  2. const pool = createPool({
  3. host: '127.0.0.1',
  4. user: 'root',
  5. password: 'Jing@123',
  6. database: 'shopping',
  7. waitForConnections: true,
  8. connectionLimit: 10,
  9. maxIdle: 10, // max idle connections, the default value is the same as `connectionLimit`
  10. idleTimeout: 60000, // idle connections timeout, in milliseconds, the default value 60000
  11. queueLimit: 0,
  12. });
  13. export async function query(sql, values) {
  14. try {
  15. let [res] = await pool.query(sql, values);
  16. return res;
  17. } catch (error) {
  18. console.log('====', error);
  19. return Promise.reject(error);
  20. }
  21. }
  22. // 定义一个数据库的中间件:作用使得每个中间件函数的ctx对象都可以具有query方法
  23. export async function DBMiddleware(ctx, next) {
  24. ctx.app.context.execute = query;
  25. await next();
  26. }
  27. export default pool;