import * as api from '../../client/src/api/api'; import Knex from 'knex'; import { sha512 } from 'js-sha512'; import { DBErrorKind, DBError } from '../endpoints/types'; export async function createUser(user: api.User, knex: Knex): Promise { return await knex.transaction(async (trx) => { try { // check if the user already exists const newUser = (await trx .select('id') .from('users') .where({ email: user.email }))[0]; if (newUser) { let e: DBError = { name: "DBError", kind: DBErrorKind.ResourceConflict, message: "User with given e-mail already exists.", } throw e; } // Create the new user. const passwordHash = sha512(user.password); const userId = (await trx('users') .insert({ email: user.email, passwordHash: passwordHash, }) .returning('id') // Needed for Postgres )[0]; return userId; } catch (e) { trx.rollback(); } }) }