Skip to content

Commit

Permalink
feat: add super like count query
Browse files Browse the repository at this point in the history
  • Loading branch information
teodorus-nathaniel committed Dec 29, 2023
1 parent c2b6e6b commit 841ddd4
Show file tree
Hide file tree
Showing 10 changed files with 141 additions and 19 deletions.
15 changes: 0 additions & 15 deletions src/components/utils/datahub-queue/super-likes.ts

This file was deleted.

43 changes: 43 additions & 0 deletions src/components/utils/datahub/super-likes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { SocialCallDataArgs, socialCallName } from '@subsocial/data-hub-sdk'
import axios from 'axios'
import { gql } from 'graphql-request'
import { createSocialDataEventPayload, DatahubParams, datahubQueryRequest } from './utils'

// QUERIES
const GET_SUPER_LIKE_COUNTS = gql`
query GetSuperLikeCounts($postIds: [String!]!) {
activeStakingSuperLikeCountsByPost(args: { postPersistentIds: $postIds }) {
persistentPostId
count
}
}
`
export async function getSuperLikeCounts(postIds: string[]) {
const res = (await datahubQueryRequest({
document: GET_SUPER_LIKE_COUNTS,
variables: { postIds },
})) as {
activeStakingSuperLikeCountsByPost: {
persistentPostId: string
count: number
}[]
}

return res.activeStakingSuperLikeCountsByPost.map(item => ({
postId: item.persistentPostId,
count: item.count,
}))
}

// MUTATIONS
export async function createSuperLike(
params: DatahubParams<SocialCallDataArgs<'synth_active_staking_create_super_like'>>,
) {
const input = createSocialDataEventPayload(
socialCallName.synth_active_staking_create_super_like,
params,
)

const res = await axios.post('/api/datahub/super-likes', input)
return res.data
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,25 @@ import {
SocialEventDataType,
socialEventProtVersion,
} from '@subsocial/data-hub-sdk'
import { GraphQLClient, RequestOptions, Variables } from 'graphql-request'
import { datahubQueryUrl } from 'src/config/env'

// QUERIES
export function datahubQueryRequest<T, V extends Variables = Variables>(
config: RequestOptions<V, T>,
) {
if (!datahubQueryUrl) throw new Error('Datahub (Query) config is not set')

const TIMEOUT = 10 * 1000 // 10 seconds
const client = new GraphQLClient(datahubQueryUrl, {
timeout: TIMEOUT,
...config,
})

return client.request({ url: datahubQueryUrl, ...config })
}

// MUTATIONS
export type DatahubParams<T> = {
address: string

Expand Down
6 changes: 4 additions & 2 deletions src/components/voting/SuperLike.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,21 @@ import { Button, ButtonProps } from 'antd'
import clsx from 'clsx'
import { CSSProperties } from 'react'
import { AiFillHeart, AiOutlineHeart } from 'react-icons/ai'
import { useSuperLikeCount } from 'src/rtk/features/activeStaking/superLikeCountsHooks'
import { useOpenCloseOnBoardingModal } from 'src/rtk/features/onBoarding/onBoardingHooks'
import { useAuth } from '../auth/AuthContext'
import { useMyAddress } from '../auth/MyAccountsContext'
import { IconWithLabel } from '../utils'
import { createSuperLike } from '../utils/datahub-queue/super-likes'
import { createSuperLike } from '../utils/datahub/super-likes'

export type SuperLikeProps = ButtonProps & {
post: PostStruct
}

export default function SuperLike({ post, ...props }: SuperLikeProps) {
const count = useSuperLikeCount(post.id)
const isActive = true
const count = 21

const openOnBoardingModal = useOpenCloseOnBoardingModal()
const myAddress = useMyAddress()

Expand Down
2 changes: 2 additions & 0 deletions src/config/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ export const datahubQueueConfig = {
token: process.env['DATAHUB_QUEUE_TOKEN'],
}

export const datahubQueryUrl = process.env['NEXT_PUBLIC_DATAHUB_QUERY_URL']

/**
* Enable or disable the available features of this web app by overriding them in the .env file.
*/
Expand Down
2 changes: 2 additions & 0 deletions src/rtk/app/rootReducer.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { combineReducers } from '@reduxjs/toolkit'
import myAccount from '../features/accounts/myAccountSlice'
import spaceEditors from '../features/accounts/spaceEditorsSlice'
import superLikeCounts from '../features/activeStaking/superLikeCountsSlice'
import chainsInfo from '../features/chainsInfo/chainsInfoSlice'
import chat from '../features/chat/chatSlice'
import enableConfirmation from '../features/confirmationPopup/enableConfirmationSlice'
Expand Down Expand Up @@ -55,6 +56,7 @@ const rootReducer = combineReducers({
stakes,
totalStake,
creatorsList,
superLikeCounts,
})

export type RootState = ReturnType<typeof rootReducer>
Expand Down
6 changes: 4 additions & 2 deletions src/rtk/app/wrappers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,12 +207,14 @@ export function createSimpleFetchWrapper<Args, ReturnValue>({
async (allArgs, { getState, dispatch }): Promise<ReturnValue> => {
const { reload, ...args } = allArgs
const id = JSON.stringify(sortKeysRecursive(args))

const alreadyFetchedPromise = currentlyFetchingMap.get(id)
if (alreadyFetchedPromise) return alreadyFetchedPromise

if (!reload) {
const fetchedData = getCachedData(getState(), allArgs)
if (fetchedData && !shouldFetchCondition?.(fetchedData)) return fetchedData
}
const alreadyFetchedPromise = currentlyFetchingMap.get(id)
if (alreadyFetchedPromise) return alreadyFetchedPromise

const promise = fetchData(allArgs)
currentlyFetchingMap.set(id, promise)
Expand Down
6 changes: 6 additions & 0 deletions src/rtk/features/activeStaking/superLikeCountsHooks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { useAppSelector } from 'src/rtk/app/store'
import { selectPostSuperLikeCount } from './superLikeCountsSlice'

export function useSuperLikeCount(postId: string) {
return useAppSelector(state => selectPostSuperLikeCount(state, postId)?.count ?? 0)
}
60 changes: 60 additions & 0 deletions src/rtk/features/activeStaking/superLikeCountsSlice.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { createEntityAdapter, createSlice } from '@reduxjs/toolkit'
import { getSuperLikeCounts } from 'src/components/utils/datahub/super-likes'
import { RootState } from 'src/rtk/app/rootReducer'
import { createSimpleFetchWrapper } from 'src/rtk/app/wrappers'

export type SuperLikeCount = {
postId: string
count: number
}

const sliceName = 'superLikesCounts'

const adapter = createEntityAdapter<SuperLikeCount>({
selectId: data => data.postId,
})
const selectors = adapter.getSelectors<RootState>(state => state.superLikeCounts)

export const selectPostSuperLikeCount = selectors.selectById
export const selectPostSuperLikeCounts = selectors.selectEntities

export const fetchSuperLikeCounts = createSimpleFetchWrapper<
{ postIds: string[] },
SuperLikeCount[]
>({
fetchData: async function ({ postIds }) {
return await getSuperLikeCounts(postIds)
},
saveToCacheAction: data => slice.actions.setSuperLikeCounts(data),
getCachedData: (state, { postIds }) => {
const entities = selectPostSuperLikeCounts(state)
let isEveryDataCached = true

const postEntities: SuperLikeCount[] = []
for (let i = 0; i < postIds.length; i++) {
const postId = postIds[i]
if (!entities[postId]) {
isEveryDataCached = false
break
} else {
postEntities.push(entities[postId]!)
}
}

if (isEveryDataCached) {
return postEntities
}
return undefined
},
sliceName,
})

const slice = createSlice({
name: sliceName,
initialState: adapter.getInitialState(),
reducers: {
setSuperLikeCounts: adapter.upsertMany,
},
})

export default slice.reducer
2 changes: 2 additions & 0 deletions src/rtk/features/posts/postsSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import {
SpaceData,
SpaceStruct,
} from 'src/types'
import { fetchSuperLikeCounts } from '../activeStaking/superLikeCountsSlice'
import { Content, fetchContents, selectPostContentById } from '../contents/contentsSlice'
import { fetchProfileSpaces } from '../profiles/profilesSlice'
import { fetchMyReactionsByPostIds } from '../reactions/myPostReactionsSlice'
Expand Down Expand Up @@ -241,6 +242,7 @@ export const fetchPosts = createAsyncThunk<PostStruct[], FetchPostsArgs, ThunkAp
)

const fetches: Promise<any>[] = []
fetches.push(dispatch(fetchSuperLikeCounts({ postIds: entities.map(({ id }) => id) })))
if (withOwner) {
const ids = getUniqueOwnerIds(entities)
const prefetchedData = generatePrefetchData<ProfileSpaceIdByAccount>(
Expand Down

0 comments on commit 841ddd4

Please sign in to comment.