You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
35 lines
1.0 KiB
35 lines
1.0 KiB
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<number> { |
|
return await knex.transaction(async (trx) => { |
|
// 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; |
|
}) |
|
} |