models
ディレクトリを作成する
モデルは、競合しやすいので、UserModel
のように〇〇Model
にする。
models/user.jsexport default class UserModel { constructor(name) { this.name = name } // インスタンスメソッド sayName() { console.log(this.name) } // クラスメソッド(静的メソッド) static async findAndCreate(uid) { const res = await fetch('/api/user/get-and-create', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ uid: uid }) }) const data = await res.json() return new UserModel(data.name) // インスタンス化して返す } }
const user = await UserModel.findAndCreate(uid) console.log(user.name) user.sayHello()