简体   繁体   中英

sqllite3 Node.js database controller (this.dao.run is not a function)

Im trying to design database sqllite3 controller but Im getting an error:

TypeError: this.dao.run is not a function

at ProjectRepository.createTable (/home/alexa/abc/project_repository:13:21)
at main (/home/alexa/abc/main.js:14:15)

Why? I really would like to write a bit higher lever app

My structure: dao.js

const sqlite3 = require('sqlite3')
class AppDAO {
  constructor(dbFilePath) {
    this.dao = new sqlite3.Database(dbFilePath, (err) => {
      if (err) {
        console.log('Could not connect to database', err)
      } else {
        console.log('Connected to database')
      }
    })
  }
}

module.exports = AppDAO

ProjectRepository:

class ProjectRepository {
  constructor(dao) {
    this.dao = dao;
  }

  createTable() {
    const sql = `
    CREATE TABLE IF NOT EXISTS projects (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      name TEXT)`;
    return this.dao.run(sql);
  }

  create(name) {
    return this.dao.run(
        'INSERT INTO projects (name) VALUES (?)',
        [name]);
  }
}

module.exports = ProjectRepository;

Main class:

const AppDAO = require('./dao');
const ProjectRepository = require('./project_repository');


// eslint-disable-next-line require-jsdoc
function main() {
  const dao = new AppDAO('./database.sqlite3');
  const blogProjectData = {name: 'Write Node.js - SQLite Tutorial'};
  const projectRepo = new ProjectRepository(dao);


  projectRepo.createTable()
      .then(() => projectRepo.createTable())
      .then(() => projectRepo.create(blogProjectData.name));
}

main();

The dao variable you pass to new ProjectRepository(dao) holds an object of type AppDAO and your AppDAO class does not have a function run .

So either call run on the dao property of your AppDAO object.

  createTable() {
    const sql = `
    CREATE TABLE IF NOT EXISTS projects (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      name TEXT)`;
    return this.dao.dao.run(sql);
  }

Or add a run function for AppDAO that forwards the call to dao property using Function.prototype.apply()

class AppDAO {
  constructor(dbFilePath) {
    this.dao = new sqlite3.Database(dbFilePath, (err) => {
      if (err) {
        console.log('Could not connect to database', err)
      } else {
        console.log('Connected to database')
      }
    })
  }

  run() {
     // forward the call to the run function of the dao property
     return this.dao.apply(this.dao, arguments);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM