Migrate changeUserInfo function to v2 (#626)

This commit is contained in:
Marshall Polaris 2022-07-08 15:00:03 -07:00 committed by GitHub
parent 93b293ca0e
commit ed0544212d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 32 additions and 65 deletions

View File

@ -1,5 +1,5 @@
import * as functions from 'firebase-functions'
import * as admin from 'firebase-admin' import * as admin from 'firebase-admin'
import { z } from 'zod'
import { getUser } from './utils' import { getUser } from './utils'
import { Contract } from '../../common/contract' import { Contract } from '../../common/contract'
@ -11,37 +11,23 @@ import {
} from '../../common/util/clean-username' } from '../../common/util/clean-username'
import { removeUndefinedProps } from '../../common/util/object' import { removeUndefinedProps } from '../../common/util/object'
import { Answer } from '../../common/answer' import { Answer } from '../../common/answer'
import { APIError, newEndpoint, validate } from './api'
export const changeUserInfo = functions const bodySchema = z.object({
.runWith({ minInstances: 1 }) username: z.string().optional(),
.https.onCall( name: z.string().optional(),
async ( avatarUrl: z.string().optional(),
data: { })
username?: string
name?: string
avatarUrl?: string
},
context
) => {
const userId = context?.auth?.uid
if (!userId) return { status: 'error', message: 'Not authorized' }
const user = await getUser(userId) export const changeuserinfo = newEndpoint({}, async (req, auth) => {
if (!user) return { status: 'error', message: 'User not found' } const { username, name, avatarUrl } = validate(bodySchema, req.body)
const { username, name, avatarUrl } = data const user = await getUser(auth.uid)
if (!user) throw new APIError(400, 'User not found')
return await changeUser(user, { username, name, avatarUrl }) await changeUser(user, { username, name, avatarUrl })
.then(() => { return { message: 'Successfully changed user info.' }
console.log('succesfully changed', user.username, 'to', data) })
return { status: 'success' }
})
.catch((e) => {
console.log('Error', e.message)
return { status: 'error', message: e.message }
})
}
)
export const changeUser = async ( export const changeUser = async (
user: User, user: User,
@ -55,14 +41,14 @@ export const changeUser = async (
if (update.username) { if (update.username) {
update.username = cleanUsername(update.username) update.username = cleanUsername(update.username)
if (!update.username) { if (!update.username) {
throw new Error('Invalid username') throw new APIError(400, 'Invalid username')
} }
const sameNameUser = await transaction.get( const sameNameUser = await transaction.get(
firestore.collection('users').where('username', '==', update.username) firestore.collection('users').where('username', '==', update.username)
) )
if (!sameNameUser.empty) { if (!sameNameUser.empty) {
throw new Error('Username already exists') throw new APIError(400, 'Username already exists')
} }
} }
@ -104,17 +90,10 @@ export const changeUser = async (
) )
const answerUpdate: Partial<Answer> = removeUndefinedProps(update) const answerUpdate: Partial<Answer> = removeUndefinedProps(update)
await transaction.update(userRef, userUpdate) transaction.update(userRef, userUpdate)
commentSnap.docs.forEach((d) => transaction.update(d.ref, commentUpdate))
await Promise.all( answerSnap.docs.forEach((d) => transaction.update(d.ref, answerUpdate))
commentSnap.docs.map((d) => transaction.update(d.ref, commentUpdate)) contracts.docs.forEach((d) => transaction.update(d.ref, contractUpdate))
)
await Promise.all(
answerSnap.docs.map((d) => transaction.update(d.ref, answerUpdate))
)
await contracts.docs.map((d) => transaction.update(d.ref, contractUpdate))
}) })
} }

View File

@ -3,7 +3,6 @@ import * as admin from 'firebase-admin'
admin.initializeApp() admin.initializeApp()
// v1 // v1
// export * from './keep-awake'
export * from './claim-manalink' export * from './claim-manalink'
export * from './transact' export * from './transact'
export * from './stripe' export * from './stripe'
@ -16,7 +15,6 @@ export * from './unsubscribe'
export * from './update-metrics' export * from './update-metrics'
export * from './update-stats' export * from './update-stats'
export * from './backup-db' export * from './backup-db'
export * from './change-user-info'
export * from './market-close-notifications' export * from './market-close-notifications'
export * from './add-liquidity' export * from './add-liquidity'
export * from './on-create-answer' export * from './on-create-answer'
@ -33,6 +31,7 @@ export * from './on-create-txn'
// v2 // v2
export * from './health' export * from './health'
export * from './change-user-info'
export * from './place-bet' export * from './place-bet'
export * from './sell-bet' export * from './sell-bet'
export * from './sell-shares' export * from './sell-shares'

View File

@ -50,6 +50,10 @@ export function getFunctionUrl(name: string) {
} }
} }
export function changeUserInfo(params: any) {
return call(getFunctionUrl('changeuserinfo'), 'POST', params)
}
export function createMarket(params: any) { export function createMarket(params: any) {
return call(getFunctionUrl('createmarket'), 'POST', params) return call(getFunctionUrl('createmarket'), 'POST', params)
} }

View File

@ -42,16 +42,6 @@ export const createUser: () => Promise<User | null> = () => {
.catch(() => null) .catch(() => null)
} }
export const changeUserInfo = (data: {
username?: string
name?: string
avatarUrl?: string
}) => {
return cloudFunction('changeUserInfo')(data)
.then((r) => r.data as { status: string; message?: string })
.catch((e) => ({ status: 'error', message: e.message }))
}
export const addLiquidity = (data: { amount: number; contractId: string }) => { export const addLiquidity = (data: { amount: number; contractId: string }) => {
return cloudFunction('addLiquidity')(data) return cloudFunction('addLiquidity')(data)
.then((r) => r.data as { status: string }) .then((r) => r.data as { status: string })

View File

@ -9,7 +9,7 @@ import { Title } from 'web/components/title'
import { usePrivateUser, useUser } from 'web/hooks/use-user' import { usePrivateUser, useUser } from 'web/hooks/use-user'
import { formatMoney } from 'common/util/format' import { formatMoney } from 'common/util/format'
import { cleanDisplayName, cleanUsername } from 'common/util/clean-username' import { cleanDisplayName, cleanUsername } from 'common/util/clean-username'
import { changeUserInfo } from 'web/lib/firebase/fn-call' import { changeUserInfo } from 'web/lib/firebase/api-call'
import { uploadImage } from 'web/lib/firebase/storage' import { uploadImage } from 'web/lib/firebase/storage'
import { Col } from 'web/components/layout/col' import { Col } from 'web/components/layout/col'
import { Row } from 'web/components/layout/row' import { Row } from 'web/components/layout/row'
@ -85,12 +85,9 @@ export default function ProfilePage() {
if (newName) { if (newName) {
setName(newName) setName(newName)
await changeUserInfo({ name: newName }).catch((_) =>
await changeUserInfo({ name: newName }) setName(user?.name || '')
.catch(() => ({ status: 'error' })) )
.then((r) => {
if (r.status === 'error') setName(user?.name || '')
})
} else { } else {
setName(user?.name || '') setName(user?.name || '')
} }
@ -101,11 +98,9 @@ export default function ProfilePage() {
if (newUsername) { if (newUsername) {
setUsername(newUsername) setUsername(newUsername)
await changeUserInfo({ username: newUsername }) await changeUserInfo({ username: newUsername }).catch((_) =>
.catch(() => ({ status: 'error' })) setUsername(user?.username || '')
.then((r) => { )
if (r.status === 'error') setUsername(user?.username || '')
})
} else { } else {
setUsername(user?.username || '') setUsername(user?.username || '')
} }