All files / src/lib/db user-store.ts

95.31% Statements 61/64
100% Branches 11/11
92% Functions 23/25
95.16% Lines 59/62

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205        69x   69x                 69x   69x                     69x   69x 1640x 895x   745x     190x   107x             69x 421x 11x   410x                                   87x 87x       9x 9x       98x     97x       13x   12x 5x   7x       124x 124x 27x   97x 83x   14x 13x   1x       63x 62x 62x       35x 35x       1x           1x       53x       53x       34x 34x       3x       7x       7x 1x     6x       14x           5x       22x             32x       2x     2x                             49x 49x       69x 69x  
/* eslint camelcase: "off" */
 
import { Knex } from 'knex';
import { Logger, LogProvider } from '../logger';
import User from '../types/user';
 
import NotFoundError from '../error/notfound-error';
import {
    ICreateUser,
    IUserLookup,
    IUserSearch,
    IUserStore,
    IUserUpdateFields,
} from '../types/stores/user-store';
 
const TABLE = 'users';
 
const USER_COLUMNS = [
    'id',
    'name',
    'username',
    'email',
    'image_url',
    'login_attempts',
    'seen_at',
    'created_at',
];
 
const USER_COLUMNS_PUBLIC = ['id', 'name', 'username', 'email', 'image_url'];
 
const emptify = (value) => {
    if (!value) {
        return undefined;
    }
    return value;
};
 
const safeToLower = (s?: string) => (s ? s.toLowerCase() : s);
 
const mapUserToColumns = (user: ICreateUser) => ({
    name: user.name,
    username: user.username,
    email: safeToLower(user.email),
    image_url: user.imageUrl,
});
 
const rowToUser = (row) => {
    if (!row) {
        throw new NotFoundError('No user found');
    }
    return new User({
        id: row.id,
        name: emptify(row.name),
        username: emptify(row.username),
        email: emptify(row.email),
        imageUrl: emptify(row.image_url),
        loginAttempts: row.login_attempts,
        seenAt: row.seen_at,
        createdAt: row.created_at,
    });
};
 
class UserStore implements IUserStore {
    private db: Knex;
 
    private logger: Logger;
 
    constructor(db: Knex, getLogger: LogProvider) {
        this.db = db;
        this.logger = getLogger('user-store.ts');
    }
 
    async update(id: number, fields: IUserUpdateFields): Promise<User> {
        await this.db(TABLE).where('id', id).update(mapUserToColumns(fields));
        return this.get(id);
    }
 
    async insert(user: ICreateUser): Promise<User> {
        const rows = await this.db(TABLE)
            .insert(mapUserToColumns(user))
            .returning(USER_COLUMNS);
        return rowToUser(rows[0]);
    }
 
    async upsert(user: ICreateUser): Promise<User> {
        const id = await this.hasUser(user);
 
        if (id) {
            return this.update(id, user);
        }
        return this.insert(user);
    }
 
    buildSelectUser(q: IUserLookup): any {
        const query = this.db(TABLE);
        if (q.id) {
            return query.where('id', q.id);
        }
        if (q.email) {
            return query.where('email', safeToLower(q.email));
        }
        if (q.username) {
            return query.where('username', q.username);
        }
        throw new Error('Can only find users with id, username or email.');
    }
 
    async hasUser(idQuery: IUserLookup): Promise<number | undefined> {
        const query = this.buildSelectUser(idQuery);
        const item = await query.first('id');
        return item ? item.id : undefined;
    }
 
    async getAll(): Promise<User[]> {
        const users = await this.db.select(USER_COLUMNS).from(TABLE);
        return users.map(rowToUser);
    }
 
    async search(query: IUserSearch): Promise<User[]> {
        const users = await this.db
            .select(USER_COLUMNS_PUBLIC)
            .from(TABLE)
            .where('name', 'ILIKE', `%${query}%`)
            .orWhere('username', 'ILIKE', `${query}%`)
            .orWhere('email', 'ILIKE', `${query}%`);
        return users.map(rowToUser);
    }
 
    async getAllWithId(userIdList: number[]): Promise<User[]> {
        const users = await this.db
            .select(USER_COLUMNS_PUBLIC)
            .from(TABLE)
            .whereIn('id', userIdList);
        return users.map(rowToUser);
    }
 
    async getByQuery(idQuery: IUserLookup): Promise<User> {
        const row = await this.buildSelectUser(idQuery).first(USER_COLUMNS);
        return rowToUser(row);
    }
 
    async delete(id: number): Promise<void> {
        return this.db(TABLE).where({ id }).del();
    }
 
    async getPasswordHash(userId: number): Promise<string> {
        const item = await this.db(TABLE)
            .where('id', userId)
            .first('password_hash');
 
        if (!item) {
            throw new NotFoundError('User not found');
        }
 
        return item.password_hash;
    }
 
    async setPasswordHash(userId: number, passwordHash: string): Promise<void> {
        return this.db(TABLE).where('id', userId).update({
            password_hash: passwordHash,
        });
    }
 
    async incLoginAttempts(user: User): Promise<void> {
        return this.buildSelectUser(user).increment('login_attempts', 1);
    }
 
    async successfullyLogin(user: User): Promise<void> {
        return this.buildSelectUser(user).update({
            login_attempts: 0,
            seen_at: new Date(),
        });
    }
 
    async deleteAll(): Promise<void> {
        await this.db(TABLE).del();
    }
 
    async count(): Promise<number> {
        return this.db
            .from(TABLE)
            .count('*')
            .then((res) => Number(res[0].count));
    }
 
    destroy(): void {}
 
    async exists(id: number): Promise<boolean> {
        const result = await this.db.raw(
            `SELECT EXISTS (SELECT 1 FROM ${TABLE} WHERE id = ?) AS present`,
            [id],
        );
        const { present } = result.rows[0];
        return present;
    }
 
    async get(id: number): Promise<User> {
        const row = await this.db(TABLE).where({ id }).first();
        return rowToUser(row);
    }
}
 
module.exports = UserStore;
export default UserStore;