import { Pool } from 'pg';
import { IUserStore, BaseUser } from '@nik2208/node-auth';
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
export class PgUserStore implements IUserStore {
async findByEmail(email: string): Promise<BaseUser | null> {
const { rows } = await pool.query(
'SELECT * FROM users WHERE email = $1',
[email]
);
return rows[0] ?? null;
}
async findById(id: string): Promise<BaseUser | null> {
const { rows } = await pool.query(
'SELECT * FROM users WHERE id = $1',
[id]
);
return rows[0] ?? null;
}
async create(data: Partial<BaseUser>): Promise<BaseUser> {
const { rows } = await pool.query(
`INSERT INTO users (id, email, password, name, role, login_provider)
VALUES ($1, $2, $3, $4, $5, $6) RETURNING *`,
[crypto.randomUUID(), data.email, data.password, data.name, data.role ?? 'user', data.loginProvider ?? 'local']
);
return rows[0];
}
async updateRefreshToken(userId: string, token: string | null, expiry: Date | null): Promise<void> {
await pool.query(
'UPDATE users SET refresh_token = $1, refresh_token_expiry = $2 WHERE id = $3',
[token, expiry, userId]
);
}
}