Commit 21085f13 authored by Yuci Gou's avatar Yuci Gou
Browse files

Create EpmcBaseModel and base Identity and User models on it

parent ea978580
Pipeline #9931 failed with stages
in 9 seconds
......@@ -7,6 +7,7 @@ const components = require('./components.json')
const logger = require('winston')
module.exports = {
schema: {},
authsome: {
mode: path.resolve(__dirname, 'authsome.js'),
teams: {
......
const { transaction } = require('objection')
const BaseModel = require('@pubsweet/base-model')
const logger = require('@pubsweet/logger')
const knex = BaseModel.knex()
class EpmcBaseModel extends BaseModel {
async save() {
let trx
let saved
try {
trx = await transaction.start(knex)
if (this.id) {
saved = await this.constructor
.query(trx)
.patchAndFetchById(this.id, this.toJSON())
}
if (!saved) {
// either model has no ID or the ID was not found in the database
console.log('Objects to insert is ', this.toJSON())
saved = await this.constructor.query(trx).insertGraph(this.toJSON())
}
logger.info(`Saved ${this.constructor.name} with UUID ${saved.id}`)
await trx.commit()
} catch (error) {
await trx.rollback()
console.log('Nothing was inserted')
}
return saved
}
}
module.exports = EpmcBaseModel
const { Model } = require('objection')
const uuid = require('uuid')
const EpmcBaseModel = require('../epmc-base-model')
const { rowToEntity, entityToRow, buildQuery, runQuery } = require('../util')
const User = require('../user/data-access')
const columnNames = ['user_id', 'type', 'identifier']
const dataAccess = {
class Identity extends EpmcBaseModel {
static get tableName() {
return 'identity'
}
static get relationMappings() {
return {
user: {
relation: Model.BelongsToOneRelation,
modelClass: User,
join: {
from: 'identity.user_id',
to: 'users.id',
},
},
}
}
static get schema() {
return {
properties: {
id: { type: 'uuid' },
user_id: { type: 'uuid' },
email: { type: 'string' },
passwordHash: { type: 'string' },
displayName: { type: 'string' },
},
}
}
async selectById(id) {
const { rows } = await runQuery(
buildQuery
......@@ -15,12 +47,12 @@ const dataAccess = {
throw new Error('Identity not found')
}
return rowToEntity(rows[0])
},
}
async selectAll() {
const { rows } = await runQuery(buildQuery.select().from('identity'))
return rows.map(rowToEntity)
},
}
async insert(identity) {
const row = entityToRow(identity, columnNames)
......@@ -28,7 +60,7 @@ const dataAccess = {
const query = buildQuery.insert(row).into('identity')
await runQuery(query)
return row.id
},
}
update(identity) {
const row = entityToRow(identity, columnNames)
......@@ -37,7 +69,7 @@ const dataAccess = {
.table('identity')
.where('id', identity.id)
return runQuery(query)
},
}
delete(id) {
return runQuery(
......@@ -46,6 +78,7 @@ const dataAccess = {
.from('identity')
.where({ id }),
)
},
}
}
module.exports = dataAccess
module.exports = Identity
const lodash = require('lodash')
const dataAccess = require('./data-access')
const Identity = require('./data-access')
const empty = {}
const IdentityManager = {
find: dataAccess.selectById,
delete: dataAccess.delete,
find: Identity.selectById,
delete: Identity.delete,
new: () => lodash.cloneDeep(empty),
save: async identity => {
let id = { identity }
if (identity.id) {
const updated = await dataAccess.update(identity)
const updated = await Identity.update(identity)
if (!updated) {
throw new Error('Identity not found')
}
} else {
id = await dataAccess.insert(identity)
id = await Identity.insert(identity)
}
return { ...identity, id }
},
modelName: 'Identity',
model: Identity,
}
module.exports = IdentityManager
const { Model } = require('objection')
const uuid = require('uuid')
const EpmcBaseModel = require('../epmc-base-model')
const { rowToEntity, entityToRow, buildQuery, runQuery } = require('../util')
const columnNames = ['default_identity']
......@@ -14,14 +16,57 @@ const joinQuery = buildQuery
.join('identity', 'user.id', 'identity.user_id')
.groupBy('user.id')
const dataAccess = {
class User extends EpmcBaseModel {
static get tableName() {
return 'users'
}
static get schema() {
return {
properties: {
id: { type: 'uuid' },
defaultIdentity: { type: 'string' },
},
}
}
static get relationMappings() {
const Identity = require('../identity/data-access')
return {
identity: {
relation: Model.HasManyRelation,
modelClass: Identity,
join: {
from: 'users.id',
to: 'identity.user_id',
},
},
}
}
async find(id) {
return {
id: '2cfae398-bbe7-4483-afd9-7dd1862c1db3',
type: 'user',
admin: true,
email: 'admin@example.com',
teams: [],
username: 'admin',
fragments: [],
collections: [],
passwordHash:
'$2b$12$afw/QukiWHP.aFN0ciL2weAhWo98Yj/PnZkyFxk/J72FkPFAerD5K',
}
}
async selectById(id) {
const rows = await runQuery(joinQuery.clone().where('user.id', id))
if (!rows.length) {
throw new Error('User not found')
}
return rowToEntity(rows[0])
},
}
async selectByProfileId(profileId) {
const rows = await runQuery(
......@@ -31,12 +76,12 @@ const dataAccess = {
throw new Error('User not found')
}
return rowToEntity(rows[0])
},
}
async selectAll() {
const rows = await runQuery(joinQuery)
return rows.map(rowToEntity)
},
}
async insert(user) {
const row = entityToRow(user, columnNames)
......@@ -44,7 +89,7 @@ const dataAccess = {
const query = buildQuery.insert(row).into('user')
await runQuery(query)
return row.id
},
}
update(user) {
const row = entityToRow(user, columnNames)
......@@ -53,7 +98,7 @@ const dataAccess = {
.table('user')
.where('id', user.id)
return runQuery(query)
},
}
delete(id) {
return runQuery(
......@@ -62,6 +107,6 @@ const dataAccess = {
.from('user')
.where({ id }),
)
},
}
}
module.exports = dataAccess
module.exports = User
const IdentityManager = require('../identity')
const dataAccess = require('./data-access')
const User = require('./data-access')
const UserManager = {
find: async uuid => {
const dbUser = await dataAccess.selectById(uuid)
const dbUser = await User.selectById(uuid)
return UserManager(dbUser)
},
findByProfileId: async profileId => {
const dbUser = await dataAccess.selectByProfileId(profileId)
const dbUser = await User.selectByProfileId(profileId)
return UserManager(dbUser)
},
findOrCreate: async profileId => {
let dbUser
try {
dbUser = await dataAccess.selectByProfileId(profileId)
dbUser = await User.selectByProfileId(profileId)
} catch (err) {
if (err.message !== 'User not found') {
throw err
......@@ -27,18 +27,18 @@ const UserManager = {
return UserManager(dbUser)
},
getUuidForProfile: async profileId => {
const dbUser = await dataAccess.selectByProfileId(profileId)
const dbUser = await User.selectByProfileId(profileId)
return dbUser.id
},
save: async user => {
let id = { user }
if (user.id) {
const updated = await dataAccess.update(user)
const updated = await User.update(user)
if (!updated) {
throw new Error('User not found')
}
} else {
id = await dataAccess.insert(user)
id = await User.insert(user)
}
if (user.identities) {
......@@ -54,7 +54,7 @@ const UserManager = {
modelName: 'User',
model: dataAccess,
model: User,
}
module.exports = UserManager
......@@ -144,6 +144,14 @@
dependencies:
humps "^2.0.1"
 
"@pubsweet/base-model@^1.0.9":
version "1.0.9"
resolved "https://registry.yarnpkg.com/@pubsweet/base-model/-/base-model-1.0.9.tgz#ac76253dd457f33bb6bd91e6806df9768f13a429"
integrity sha512-NAa/qyoLY/eujXoNk/TSicmUoWqfM2jLfbOT6nw0e9SVRjs61SS150OxYnYUss7gGq2lxX0fS2oGI9pVd6asuA==
dependencies:
objection "^1.2.3"
pubsweet-server "^10.1.0"
"@pubsweet/component-send-email@^0.2.4":
version "0.2.4"
resolved "https://registry.yarnpkg.com/@pubsweet/component-send-email/-/component-send-email-0.2.4.tgz#e0d73769b804656d7ed5cebf1d2b50afaa378a02"
......@@ -8042,6 +8050,15 @@ object.values@^1.0.4:
function-bind "^1.1.0"
has "^1.0.1"
 
objection@^1.2.3:
version "1.4.0"
resolved "https://registry.yarnpkg.com/objection/-/objection-1.4.0.tgz#18ddcdc121ae9b5d1e8e88b10fd0a6c96134f422"
integrity sha512-JO5M6FqnNfw7uN4WhLABX0A1d65o2p4ILSiWRfbG3X3MAv70CH5C1rfBw7S8HvyUs2EDpCekIdkgZnAuT8sbaQ==
dependencies:
ajv "^6.1.1"
bluebird "^3.5.1"
lodash "^4.17.4"
objection@^1.3.0:
version "1.3.0"
resolved "https://registry.yarnpkg.com/objection/-/objection-1.3.0.tgz#2b7e41d4b44a5c1abcb40e34e7ef6347e8bb683d"
......@@ -9092,7 +9109,7 @@ promisify-event@^1.0.0:
dependencies:
pinkie-promise "^2.0.0"
 
prompt@^1.0.0, "prompt@github:flatiron/prompt#1c95d1d8d333b5fbc13fa5f0619f3dcf0d514f87":
prompt@^1.0.0, prompt@flatiron/prompt#1c95d1d8d333b5fbc13fa5f0619f3dcf0d514f87:
version "1.0.0"
resolved "https://codeload.github.com/flatiron/prompt/tar.gz/1c95d1d8d333b5fbc13fa5f0619f3dcf0d514f87"
integrity sha1-jlcSPDlquYiJf7Mn/Trtw+c15P4=
......@@ -12607,6 +12624,11 @@ w3c-keyname@^1.1.8:
resolved "https://registry.yarnpkg.com/w3c-keyname/-/w3c-keyname-1.1.8.tgz#4e2219663760fd6535b7a1550f1552d71fc9372c"
integrity sha512-2HAdug8GTiu3b4NYhssdtY8PXRue3ICnh1IlxvZYl+hiINRq0GfNWei3XOPDg8L0PsxbmYjWVLuLj6BMRR/9vA==
 
waait@^1.0.2:
version "1.0.2"
resolved "https://registry.yarnpkg.com/waait/-/waait-1.0.2.tgz#c234ed748a032cb7d5e83cb691567c6dc545b37d"
integrity sha512-amvD7uRx48U2gXOgzwV7PbcpSy8O3Fect2SqiLbBIVH9Zh0UMnDWckSLnsdKNwq7pvarWnPWrpYad2P3pgmRYw==
walker@~1.0.5:
version "1.0.7"
resolved "https://registry.yarnpkg.com/walker/-/walker-1.0.7.tgz#2f7f9b8fd10d677262b18a884e28d19618e028fb"
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment