Rewrite login query

This commit is contained in:
Zhiyuan Zheng 2020-12-13 22:10:54 +01:00
parent dc9870beaf
commit 8ed008b961
No known key found for this signature in database
GPG Key ID: 078A93AB607D85E0
3 changed files with 88 additions and 70 deletions

View File

@ -31,20 +31,21 @@ import { ButtonRow } from '@components/Button'
import ParseContent from '@root/components/ParseContent' import ParseContent from '@root/components/ParseContent'
import ShimmerPlaceholder from 'react-native-shimmer-placeholder' import ShimmerPlaceholder from 'react-native-shimmer-placeholder'
import { Feather } from '@expo/vector-icons' import { Feather } from '@expo/vector-icons'
import { applicationFetch } from '@root/utils/fetches/applicationFetch'
const Login: React.FC = () => { const Login: React.FC = () => {
const { t } = useTranslation('meRoot') const { t } = useTranslation('meRoot')
const { theme } = useTheme() const { theme } = useTheme()
const navigation = useNavigation() const navigation = useNavigation()
const dispatch = useDispatch() const dispatch = useDispatch()
const [instance, setInstance] = useState('') const [instanceDomain, setInstanceDomain] = useState<string | undefined>()
const [applicationData, setApplicationData] = useState<{ const [applicationData, setApplicationData] = useState<{
clientId: string clientId: string
clientSecret: string clientSecret: string
}>() }>()
const { isSuccess, isFetching, refetch, data } = useQuery( const instanceQuery = useQuery(
['Instance', { instance }], ['Instance', { instanceDomain }],
instanceFetch, instanceFetch,
{ {
enabled: false, enabled: false,
@ -52,49 +53,25 @@ const Login: React.FC = () => {
} }
) )
const onChangeText = useCallback( const applicationQuery = useQuery(
debounce( ['Application', { instanceDomain }],
text => { applicationFetch,
setInstance(text) {
setApplicationData(undefined) enabled: false,
if (text) { retry: false
refetch() }
}
},
1000,
{
trailing: true
}
),
[]
) )
useEffect(() => {
const createApplication = async () => { if (
if (applicationData) { applicationQuery.data?.client_id.length &&
return Promise.resolve() applicationQuery.data?.client_secret.length
} ) {
const formData = new FormData()
formData.append('client_name', 'test_dudu')
formData.append('redirect_uris', 'exp://127.0.0.1:19000')
formData.append('scopes', 'read write follow push')
const res = await client({
method: 'post',
instance: 'remote',
instanceDomain: instance,
url: `apps`,
body: formData
})
if (res.body?.client_id.length > 0) {
setApplicationData({ setApplicationData({
clientId: res.body.client_id, clientId: applicationQuery.data.client_id,
clientSecret: res.body.client_secret clientSecret: applicationQuery.data.client_secret
}) })
return Promise.resolve()
} else {
return Promise.reject()
} }
} }, [applicationQuery.data?.client_id])
const [request, response, promptAsync] = AuthSession.useAuthRequest( const [request, response, promptAsync] = AuthSession.useAuthRequest(
{ {
@ -104,10 +81,9 @@ const Login: React.FC = () => {
redirectUri: 'exp://127.0.0.1:19000' redirectUri: 'exp://127.0.0.1:19000'
}, },
{ {
authorizationEndpoint: `https://${instance}/oauth/authorize` authorizationEndpoint: `https://${instanceDomain}/oauth/authorize`
} }
) )
useEffect(() => { useEffect(() => {
;(async () => { ;(async () => {
if (request?.clientId) { if (request?.clientId) {
@ -115,7 +91,6 @@ const Login: React.FC = () => {
} }
})() })()
}, [request]) }, [request])
useEffect(() => { useEffect(() => {
;(async () => { ;(async () => {
if (response?.type === 'success') { if (response?.type === 'success') {
@ -131,16 +106,31 @@ const Login: React.FC = () => {
} }
}, },
{ {
tokenEndpoint: `https://${instance}/oauth/token` tokenEndpoint: `https://${instanceDomain}/oauth/token`
} }
) )
dispatch(updateLocal({ url: instance, token: accessToken })) dispatch(updateLocal({ url: instanceDomain, token: accessToken }))
navigation.navigate('Screen-Local-Root') navigation.navigate('Screen-Local-Root')
} }
})() })()
}, [response]) }, [response])
const infoRef = createRef<ShimmerPlaceholder>() const onChangeText = useCallback(
debounce(
text => {
setInstanceDomain(text)
setApplicationData(undefined)
if (text) {
instanceQuery.refetch()
}
},
1000,
{
trailing: true
}
),
[]
)
const instanceInfo = useCallback( const instanceInfo = useCallback(
({ ({
@ -152,17 +142,13 @@ const Login: React.FC = () => {
content: string content: string
parse?: boolean parse?: boolean
}) => { }) => {
if (isFetching) {
Animated.loop(infoRef.current?.getAnimated()!).start()
}
return ( return (
<View style={styles.instanceInfo}> <View style={styles.instanceInfo}>
<Text style={[styles.instanceInfoHeader, { color: theme.primary }]}> <Text style={[styles.instanceInfoHeader, { color: theme.primary }]}>
{header} {header}
</Text> </Text>
<ShimmerPlaceholder <ShimmerPlaceholder
visible={data?.uri} visible={instanceQuery.data?.uri}
stopAutoRun stopAutoRun
width={ width={
Dimensions.get('screen').width - Dimensions.get('screen').width -
@ -183,7 +169,7 @@ const Login: React.FC = () => {
</View> </View>
) )
}, },
[data?.uri, isFetching] [instanceQuery.data?.uri]
) )
return ( return (
@ -208,29 +194,41 @@ const Login: React.FC = () => {
autoCapitalize='none' autoCapitalize='none'
autoCorrect={false} autoCorrect={false}
autoFocus autoFocus
clearButtonMode='unless-editing' clearButtonMode='never'
keyboardType='url' keyboardType='url'
textContentType='URL' textContentType='URL'
onSubmitEditing={async () => onSubmitEditing={() =>
isSuccess && data && data.uri && (await createApplication()) instanceQuery.isSuccess &&
instanceQuery.data &&
instanceQuery.data.uri &&
applicationQuery.refetch()
} }
placeholder={t('content.login.server.placeholder')} placeholder={t('content.login.server.placeholder')}
placeholderTextColor={theme.secondary} placeholderTextColor={theme.secondary}
returnKeyType='go' returnKeyType='go'
/> />
<ButtonRow <ButtonRow
onPress={async () => await createApplication()} onPress={() => {
{...(isFetching applicationQuery.refetch()
}}
{...(instanceQuery.isFetching || applicationQuery.isFetching
? { icon: 'loader' } ? { icon: 'loader' }
: { text: t('content.login.button') as string })} : { text: t('content.login.button') as string })}
disabled={!data?.uri} disabled={
!instanceQuery.data?.uri ||
instanceQuery.isFetching ||
applicationQuery.isFetching
}
/> />
</View> </View>
<View> <View>
{instanceInfo({ header: '实例名称', content: data?.title })} {instanceInfo({
header: '实例名称',
content: instanceQuery.data?.title
})}
{instanceInfo({ {instanceInfo({
header: '实例介绍', header: '实例介绍',
content: data?.short_description, content: instanceQuery.data?.short_description,
parse: true parse: true
})} })}
<View style={styles.instanceStats}> <View style={styles.instanceStats}>
@ -241,7 +239,7 @@ const Login: React.FC = () => {
</Text> </Text>
<ShimmerPlaceholder <ShimmerPlaceholder
visible={data?.stats?.user_count} visible={instanceQuery.data?.stats?.user_count}
stopAutoRun stopAutoRun
width={StyleConstants.Font.Size.M * 4} width={StyleConstants.Font.Size.M * 4}
height={StyleConstants.Font.Size.M} height={StyleConstants.Font.Size.M}
@ -249,7 +247,7 @@ const Login: React.FC = () => {
<Text <Text
style={[styles.instanceInfoContent, { color: theme.primary }]} style={[styles.instanceInfoContent, { color: theme.primary }]}
> >
{data?.stats?.user_count} {instanceQuery.data?.stats?.user_count}
</Text> </Text>
</ShimmerPlaceholder> </ShimmerPlaceholder>
</View> </View>
@ -260,7 +258,7 @@ const Login: React.FC = () => {
</Text> </Text>
<ShimmerPlaceholder <ShimmerPlaceholder
visible={data?.stats?.user_count} visible={instanceQuery.data?.stats?.user_count}
stopAutoRun stopAutoRun
width={StyleConstants.Font.Size.M * 4} width={StyleConstants.Font.Size.M * 4}
height={StyleConstants.Font.Size.M} height={StyleConstants.Font.Size.M}
@ -268,7 +266,7 @@ const Login: React.FC = () => {
<Text <Text
style={[styles.instanceInfoContent, { color: theme.primary }]} style={[styles.instanceInfoContent, { color: theme.primary }]}
> >
{data?.stats?.status_count} {instanceQuery.data?.stats?.status_count}
</Text> </Text>
</ShimmerPlaceholder> </ShimmerPlaceholder>
</View> </View>
@ -279,7 +277,7 @@ const Login: React.FC = () => {
</Text> </Text>
<ShimmerPlaceholder <ShimmerPlaceholder
visible={data?.stats?.user_count} visible={instanceQuery.data?.stats?.user_count}
stopAutoRun stopAutoRun
width={StyleConstants.Font.Size.M * 4} width={StyleConstants.Font.Size.M * 4}
height={StyleConstants.Font.Size.M} height={StyleConstants.Font.Size.M}
@ -287,7 +285,7 @@ const Login: React.FC = () => {
<Text <Text
style={[styles.instanceInfoContent, { color: theme.primary }]} style={[styles.instanceInfoContent, { color: theme.primary }]}
> >
{data?.stats?.domain_count} {instanceQuery.data?.stats?.domain_count}
</Text> </Text>
</ShimmerPlaceholder> </ShimmerPlaceholder>
</View> </View>

View File

@ -0,0 +1,20 @@
import client from '@api/client'
export const applicationFetch = async (
key: string,
{ instanceDomain, body }: { instanceDomain: string; body: FormData }
) => {
const formData = new FormData()
formData.append('client_name', 'test_dudu')
formData.append('redirect_uris', 'exp://127.0.0.1:19000')
formData.append('scopes', 'read write follow push')
const res = await client({
method: 'post',
instance: 'remote',
instanceDomain,
url: `apps`,
body: formData
})
return Promise.resolve(res.body)
}

View File

@ -2,12 +2,12 @@ import client from '@api/client'
export const instanceFetch = async ( export const instanceFetch = async (
key: string, key: string,
{ instance }: { instance: string } { instanceDomain }: { instanceDomain: string }
) => { ) => {
const res = await client({ const res = await client({
method: 'get', method: 'get',
instance: 'remote', instance: 'remote',
instanceDomain: instance, instanceDomain,
url: `instance` url: `instance`
}) })
return Promise.resolve(res.body) return Promise.resolve(res.body)