NodeJS 如何将SQlite反序列化为TS类?

0tdrvxhp  于 2023-06-22  发布在  Node.js
关注(0)|答案(1)|浏览(155)

使用Electron主包中的Sqlite3,我能够创建表、插入行并读取这些行。如何示例化读入定义类的行?示例:

export const GetAllObjs = (): Obj[] => {
  const query = db.prepare("SELECT * FROM ObjTable");
  const rows= query.all();
  let objs = [] as Obj[];
  for(const row in rows as Obj[]){
    // This object only contains the index number...
    // const obj= JSON.parse(row) as Obj;

    // This does not seem to work...
    objs.push(
      {
        // How do you access the value of each column, such as row.[columnName]?
        id: row.id, 
        name: row.name 
        amount: row.amount, 
      } as Obj
    );
  }
  return objs;
};

// Example table creation (I have verified this works with DBeaver)
export const CreateObjTable = () => {
  const query = db.prepare(`
    CREATE TABLE IF NOT EXISTS ObjTable
    (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      name TEXT,
      amount INTEGER
    )
  `);
  return query.run();
};

你的建议将不胜感激🤞。我觉得很奇怪,这不是更清楚地说明。

oogrdqng

oogrdqng1#

大多数数据库操作都是异步的,所以你必须构建一个回调风格的函数,或者让它返回一个Promise。
此外,sqlite3 all()方法仅提供回调样式的API,而它返回用于链接的数据库或语句:
执行该语句并调用包含所有结果行的回调。该函数返回Statement对象以允许函数链接。

const GetAllObjs = (): Promise<Obj[]> => {
    const query = db.prepare("SELECT * FROM ObjTable");

    // Must either use a callback-style signature
    // or return a Promise to handle the asynchronous behaviour
    return new Promise((resolve, reject) => {
        let objs = [] as Obj[];

        query.all((err, rows) => {
            //          ^? any[]
            // Loop over an array with `for...of`
            for (const row of rows as Obj[]) {
                objs.push(
                    {
                        // Okay
                        id: row.id,
                        name: row.name,
                        amount: row.amount,
                    } as Obj
                );
            }

            // Resolve with the result, as a callback return will be lost
            resolve(objs);
        })
    });
};

Playground链接

相关问题