stacker.news/pages/invites/[id].js

85 lines
2.1 KiB
JavaScript
Raw Normal View History

2021-10-15 18:05:34 +00:00
import Login from '../../components/login'
import { providers, getSession } from 'next-auth/client'
2021-10-15 23:07:51 +00:00
import models from '../../api/models'
import serialize from '../../api/resolvers/serial'
import { gql } from '@apollo/client'
import { INVITE_FIELDS } from '../../fragments/invites'
import getSSRApolloClient from '../../api/ssrApollo'
import Link from 'next/link'
2021-10-15 18:05:34 +00:00
export async function getServerSideProps ({ req, res, query: { id, error = null } }) {
const session = await getSession({ req })
2021-10-15 23:07:51 +00:00
const client = await getSSRApolloClient(req)
const { data } = await client.query({
query: gql`
${INVITE_FIELDS}
{
invite(id: "${id}") {
...InviteFields
}
}`
})
if (!data?.invite) {
return {
notFound: true
}
}
2021-10-15 18:05:34 +00:00
if (session && res) {
2021-10-15 23:07:51 +00:00
try {
// attempt to send gift
// catch any errors and just ignore them for now
await serialize(models,
models.$queryRaw('SELECT invite_drain($1, $2)', session.user.id, id))
} catch (e) {
console.log(e)
}
2021-10-15 18:05:34 +00:00
res.writeHead(302, {
Location: '/'
})
res.end()
return { props: {} }
}
2021-11-11 17:38:41 +00:00
console.log(process.env.PUBLIC_URL + req.url)
2021-10-15 18:05:34 +00:00
return {
props: {
providers: await providers({ req, res }),
2021-11-11 17:38:41 +00:00
callbackUrl: process.env.PUBLIC_URL + req.url,
2021-10-15 23:07:51 +00:00
invite: data.invite,
2021-10-15 18:05:34 +00:00
error
}
}
}
2021-10-15 23:07:51 +00:00
function InviteHeader ({ invite }) {
let Inner
if (invite.revoked) {
Inner = () => <div className='text-danger'>this invite link expired</div>
} else if ((invite.limit && invite.limit <= invite.invitees.length) || invite.poor) {
Inner = () => <div className='text-danger'>this invite link has no more sats</div>
} else {
Inner = () => (
<div>
get <span className='text-success'>{invite.gift} free sats</span> from{' '}
<Link href={`/${invite.user.name}`} passHref><a>@{invite.user.name}</a></Link>{' '}
when you sign up today
</div>
)
}
return (
<h2 className='text-center pb-3'>
<Inner />
</h2>
)
}
export default function Invite ({ invite, ...props }) {
return <Login Header={() => <InviteHeader invite={invite} />} {...props} />
}