I am dealing with the work of DenoDb and trying to make the createCat function return the type Promise<CatModel>.
What is the best way to do it?
Here is my current code:
import { Model, Database, SQLite3Connector, DataTypes } from 'https://deno.land/x/denodb/mod.ts';
interface CatModel {
id: bigint;
name: string;
}
const connector = new SQLite3Connector({
filepath: './db.sqlite',
});
const db = new Database(connector);
class CatSchema extends Model {
static table = 'cats';
static fields = {
id: {
type: DataTypes.BIG_INTEGER,
primaryKey: true,
autoIncrement: true,
},
name: {
type: DataTypes.STRING,
}
};
}
db.link([CatSchema]);
await db.sync({ drop: true });
const createCat = async (name: string): Promise<CatSchema> => {
return await CatSchema.create({
name: name
});
};
const dataCat = await createCat("Three");
console.log(dataCat);
await db.close();
Deno.exit(1);
I'm trying to make a function like this:
const createCat = async (name: string): Promise<CatModel>
How to convert Promise<CatSchema> to Promise<CatModel> correctly?
I plan to hide the work with DenoDB in the CatsRepo class in the future and give only CatModel. Is this a good solution?
Model.createreturns an object which includes the id of the last inserted row as anumber, and that property is calledlastInsertId. Becausedenodbreturns anumbertype, there's not much value in usingbigintfor the id of yourCatModel, so you can just change it tonumber, then modify your function like this:so-70550010.ts: