/** @module classes */
const BaseFactory = require('../Base.js');
const TokenController = require('../../controllers/TokenController.js');
const UserController = require('../../controllers/UserController.js');
const { UserFactory, User } = require('./User');
/** Class representing a token. */
class Token {
constructor(id, token, userId, createdAt) {
this.id = id;
this.token = token;
this.userId = userId;
this.createdAt = createdAt;
}
/**
* Get the user of the token.
*
* @returns {Promise<User>}
*/
async getUser(forceRefresh = false) {
if (this.user && !forceRefresh) {
return this.user;
}
const userRecord = await new UserController().byId(this.userId);
if (!userRecord) {
return null;
}
this.user = await new UserFactory().load(userRecord).create();
return this.user;
}
/** Refreshes data from the database that has been pulled at least once before in this instance. */
async refresh() {
if (this.user) {
await this.getUser(true);
}
}
/** Deletes a token. */
async delete() {
await new TokenController().delete(this.id);
}
}
/** Class representing a token factory. */
class TokenFactory extends BaseFactory {
/** Set the id of the token. */
setId(id) {
this.id = id;
return this;
}
/** Set the token of the token. */
setToken(token) {
this.token = token;
return this;
}
/** Set the userId of the token. */
setUserId(userId) {
this.userId = userId;
return this;
}
/** Set the created at of the token. */
setCreatedAt(createdAt) {
this.createdAt = createdAt;
return this;
}
/** Load a token from a database object. */
load(dbObject) {
this.setId(dbObject.id)
this.setToken(dbObject.token)
this.setUserId(dbObject.user_id)
this.setCreatedAt(dbObject.created_at);
return this;
}
/** Create the token object. */
async create() {
return new Token(this.id, this.token, this.userId, this.createdAt);
}
}
module.exports = { Token, TokenFactory };