stacker.news/api/resolvers/user.js

58 lines
1.8 KiB
JavaScript
Raw Normal View History

2021-05-22 00:09:11 +00:00
import { AuthenticationError, UserInputError } from 'apollo-server-errors'
2021-05-21 22:32:21 +00:00
2021-03-25 19:29:24 +00:00
export default {
Query: {
me: async (parent, args, { models, me }) =>
2021-05-11 15:52:50 +00:00
me ? await models.user.findUnique({ where: { name: me.name } }) : null,
2021-04-22 22:14:32 +00:00
user: async (parent, { name }, { models }) => {
return await models.user.findUnique({ where: { name } })
},
2021-03-25 19:29:24 +00:00
users: async (parent, args, { models }) =>
2021-05-21 22:32:21 +00:00
await models.user.findMany(),
nameAvailable: async (parent, { name }, { models, me }) => {
if (!me) {
throw new AuthenticationError('you must be logged in')
}
return me.name === name || !(await models.user.findUnique({ where: { name } }))
}
2021-03-25 19:29:24 +00:00
},
2021-05-22 00:09:11 +00:00
Mutation: {
setName: async (parent, { name }, { me, models }) => {
if (!me) {
throw new AuthenticationError('you must be logged in')
}
try {
await models.user.update({ where: { name: me.name }, data: { name } })
} catch (error) {
if (error.code === 'P2002') {
throw new UserInputError('name taken')
}
throw error
}
}
},
2021-03-25 19:29:24 +00:00
User: {
2021-04-22 22:14:32 +00:00
nitems: async (user, args, { models }) => {
return await models.item.count({ where: { userId: user.id, parentId: null } })
},
ncomments: async (user, args, { models }) => {
return await models.item.count({ where: { userId: user.id, parentId: { not: null } } })
},
2021-04-27 21:30:58 +00:00
stacked: async (user, args, { models }) => {
const [{ sum }] = await models.$queryRaw`
SELECT sum("Vote".sats)
FROM "Item"
LEFT JOIN "Vote" on "Vote"."itemId" = "Item".id AND "Item"."userId" <> ${user.id}
2021-04-27 21:30:58 +00:00
WHERE "Item"."userId" = ${user.id}`
2021-05-11 15:52:50 +00:00
return sum || 0
2021-04-27 21:30:58 +00:00
},
2021-05-11 15:52:50 +00:00
sats: async (user, args, { models }) => {
return Math.floor(user.msats / 1000)
}
2021-03-25 19:29:24 +00:00
}
}