{"size": 836, "ext": "js", "max_stars_repo_path": "services/storage/dynamodb/create-realm.js", "max_stars_repo_name": "joelnet/lambda-authentication", "max_stars_repo_stars_event_min_datetime": "2017-04-07T21:42:25.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-12T15:50:43.000Z", "max_issues_repo_path": "services/storage/dynamodb/create-realm.js", "max_issues_repo_name": "joelnet/lambda-authentication", "max_issues_repo_issues_event_min_datetime": "2017-05-07T19:51:53.000Z", "max_issues_repo_issues_event_max_datetime": "2017-06-15T09:25:19.000Z", "max_forks_repo_path": "services/storage/dynamodb/create-realm.js", "max_forks_repo_name": "joelnet/serverless-authentication", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 2, "max_issues_count": 10, "max_forks_count": null, "avg_line_length": 28.8275862069, "max_line_length": 99, "alphanum_fraction": 0.6447368421}
const config = require('config')
const promisify = require('functional-helpers/promisify')
const Joi = require('joi')
const joiValidate = promisify(Joi.validate)

const schema = Joi.object().keys({
    realmId: Joi.string().regex(/^[^:]+:[^:]+$/).required(),
    owner: Joi.string().required(),
})

const toUserDoc = model => ({
    TableName: config.get('dynamodb.tables.realms'),
    Item: model,
    Expected: {
        realmId: { Exists: false }
    },
})

const rejectMessage = err =>
    Promise.reject(err.message === 'The conditional request failed' ? 'Realm already exists' : err)

/* istanbul ignore next */
module.exports = client => model => {
    const put = promisify(client.put, client)

    return joiValidate(model, schema)
        .then(model => put(toUserDoc(model)).then(() => model))
        .catch(rejectMessage)
}