Skip to content

Commit

Permalink
Merge pull request #614 from dappforce/improvement/errors
Browse files Browse the repository at this point in the history
Improve server logs
  • Loading branch information
olehmell authored Mar 20, 2024
2 parents 5dd653c + 5892eae commit 4849d64
Show file tree
Hide file tree
Showing 36 changed files with 74 additions and 7 deletions.
3 changes: 3 additions & 0 deletions src/components/chats/ChatForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import useRequestTokenAndSendMessage from '@/hooks/useRequestTokenAndSendMessage
import { showErrorToast } from '@/hooks/useToastError'
import { useConfigContext } from '@/providers/config/ConfigProvider'
import { getPostQuery } from '@/services/api/query'
import { apiInstance } from '@/services/api/utils'
import { useSendOffchainMessage } from '@/services/datahub/posts/mutation'
import {
SendMessageParams,
Expand Down Expand Up @@ -424,6 +425,8 @@ function showErrorSendingMessageToast(
}
}

apiInstance.post('/api/logger', { error: error + '' }).catch(console.error)

showErrorToast(error, title, {
toastConfig: { duration: isRateLimited ? 5000 : Infinity },
getDescription:
Expand Down
1 change: 1 addition & 0 deletions src/pages/api/create-user-id.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export default handlerWrapper({
inputSchema: bodySchema,
dataGetter: (req: NextApiRequest) => req.body,
})<ResponseData>({
errorLabel: 'create-user-id',
allowedMethods: ['POST'],
handler: async (data, _, res) => {
let userId: string
Expand Down
1 change: 1 addition & 0 deletions src/pages/api/discussion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export default handlerWrapper({
inputSchema: bodySchema,
dataGetter: (req: NextApiRequest) => req.body,
})<DiscussionDataResponse>({
errorLabel: 'discussion',
allowedMethods: ['POST'],
handler: async (data, _, res) => {
const { resourceId, spaceId, content } = data
Expand Down
1 change: 1 addition & 0 deletions src/pages/api/identities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export default handlerWrapper({
inputSchema: querySchema,
dataGetter: (req: NextApiRequest) => req.query,
})<ResponseData>({
errorLabel: 'identities',
allowedMethods: ['GET'],
handler: async (data, _, res) => {
const addresses = Array.isArray(data.addresses)
Expand Down
16 changes: 16 additions & 0 deletions src/pages/api/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { handlerWrapper } from '@/server/common'
import { z } from 'zod'

export default handlerWrapper({
inputSchema: z.object({
error: z.unknown(),
}),
dataGetter: (req) => req.body,
})({
allowedMethods: ['POST'],
errorLabel: 'logger',
handler: async (data, _, res) => {
console.error('Error logged from logger: ', data.error)
res.json({ success: true, message: 'OK' })
},
})
1 change: 1 addition & 0 deletions src/pages/api/nft.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ export default handlerWrapper({
inputSchema: querySchema,
dataGetter: (req: NextApiRequest) => req.query,
})<NftResponseData>({
errorLabel: 'nft',
allowedMethods: ['GET'],
handler: async (data, _, res) => {
const nftProperties = data
Expand Down
3 changes: 3 additions & 0 deletions src/pages/api/posts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ const GET_handler = handlerWrapper({
inputSchema: querySchema,
dataGetter: (req: NextApiRequest) => req.query,
})<ResponseData>({
errorLabel: 'posts',
allowedMethods: ['GET'],
handler: async (data, _, res) => {
const postIds = Array.isArray(data.postIds) ? data.postIds : [data.postIds]
Expand All @@ -48,6 +49,7 @@ const POST_handler = handlerWrapper({
inputSchema: bodySchema,
dataGetter: (req: NextApiRequest) => req.body,
})<{}>({
errorLabel: 'posts',
allowedMethods: ['POST'],
handler: async (data, _, res) => {
redisCallWrapper(async (redis) => {
Expand All @@ -72,6 +74,7 @@ export default function handler(req: NextApiRequest, res: NextApiResponse) {
}

const getPostsData = generateGetDataFromSquidWithBlockchainFallback(
'posts',
getPostsFromSubsocial,
{ paramToId: (param) => param, responseToId: (post) => post.id },
{
Expand Down
5 changes: 4 additions & 1 deletion src/pages/api/profiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import { redisCallWrapper } from '@/server/cache'
import { ApiResponse, handlerWrapper } from '@/server/common'
import { generateGetDataFromSquidWithBlockchainFallback } from '@/server/squid'
import {
getProfilesFromSubsocial,
SubsocialProfile,
getProfilesFromSubsocial,
} from '@/services/subsocial/profiles/fetcher'
import { toSubsocialAddress } from '@subsocial/utils'
import { NextApiRequest, NextApiResponse } from 'next'
Expand Down Expand Up @@ -34,6 +34,7 @@ const GET_handler = handlerWrapper({
inputSchema: querySchema,
dataGetter: (req: NextApiRequest) => req.query,
})<ResponseData>({
errorLabel: 'profiles',
allowedMethods: ['GET'],
handler: async (data, _, res) => {
const addresses = Array.isArray(data.addresses)
Expand All @@ -50,6 +51,7 @@ const POST_handler = handlerWrapper({
inputSchema: bodySchema,
dataGetter: (req: NextApiRequest) => req.body,
})<{}>({
errorLabel: 'profiles',
allowedMethods: ['POST'],
handler: async (data, _, res) => {
redisCallWrapper(async (redis) => {
Expand All @@ -74,6 +76,7 @@ export default function handler(req: NextApiRequest, res: NextApiResponse) {
}

export const getProfilesServer = generateGetDataFromSquidWithBlockchainFallback(
'profiles',
getProfilesFromSubsocial,
{ paramToId: (param) => param, responseToId: (response) => response.address },
{
Expand Down
1 change: 1 addition & 0 deletions src/pages/api/promo-message/decrypt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export default handlerWrapper({
dataGetter: (req: NextApiRequest) => req.body,
})<ResponseData>({
allowedMethods: ['POST'],
errorLabel: 'decrypt-promo-message',
handler: async (data, _, res) => {
let decryptedMessage

Expand Down
1 change: 1 addition & 0 deletions src/pages/api/promo-message/encrypt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export default handlerWrapper({
inputSchema: querySchema,
dataGetter: (req: NextApiRequest) => req.body,
})<ResponseData>({
errorLabel: 'encrypt-promo-message',
allowedMethods: ['POST'],
handler: async (data, _, res) => {
let encyptedMessage
Expand Down
1 change: 1 addition & 0 deletions src/pages/api/request-token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export default handlerWrapper({
inputSchema: bodySchema,
dataGetter: (req) => req.body,
})<ResponseData>({
errorLabel: 'request-token',
allowedMethods: ['POST'],
handler: async (data, _, res) => {
const isValidAddress = await validateAddress(data.address)
Expand Down
2 changes: 1 addition & 1 deletion src/pages/api/revalidation/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const handler = handlerWrapper({
inputSchema: bodySchema,
dataGetter: (req) => req.body,
})({
errorLabel: 'revalidation-chat',
allowedMethods: ['POST'],
handler: async (data, _, res) => {
try {
Expand Down Expand Up @@ -55,6 +56,5 @@ const handler = handlerWrapper({
})
}
},
errorLabel: 'Error revalidating post',
})
export default handler
2 changes: 1 addition & 1 deletion src/pages/api/revalidation/link.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const handler = handlerWrapper({
dataGetter: (req) => req.body,
})<{ data: Awaited<ReturnType<typeof getLinkMetadata>> }>({
allowedMethods: ['POST'],
errorLabel: 'revalidation-link',
handler: async (data, _, res) => {
try {
const metadata = await getLinkMetadata(data.link, true)
Expand All @@ -24,6 +25,5 @@ const handler = handlerWrapper({
})
}
},
errorLabel: 'Error revalidating link',
})
export default handler
1 change: 1 addition & 0 deletions src/pages/api/save-file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export default handlerWrapper({
inputSchema: bodySchema,
dataGetter: (req) => req.body,
})<ResponseData>({
errorLabel: 'save-file',
allowedMethods: ['POST'],
handler: async (data, _, res) => {
const { saveAndPinJson } = getIpfsApi()
Expand Down
4 changes: 2 additions & 2 deletions src/server/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export function handlerWrapper<Input extends z.ZodTypeAny>(config: {
dataGetter: (req: NextApiRequest) => unknown
}) {
return <Output>(handlerConfig: {
errorLabel?: string
errorLabel: string
handler: (
data: z.infer<Input>,
req: NextApiRequest,
Expand Down Expand Up @@ -59,7 +59,7 @@ export function handlerWrapper<Input extends z.ZodTypeAny>(config: {
try {
return await handler(params.data, req, res)
} catch (err) {
console.error(`Error in ${errorLabel || 'handler'}:`, err)
console.error(`Error in ${errorLabel} method: ${req.method}:`, err)
return res.status(500).send({
success: false,
message: 'Internal server error',
Expand Down
3 changes: 2 additions & 1 deletion src/server/squid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { redisCallWrapper } from '@/server/cache'
import { DataSource } from '@/services/subsocial/utils'

export function generateGetDataFromSquidWithBlockchainFallback<Param, Response>(
dataName: string,
getData: (params: Param[], dataSource?: DataSource) => Promise<Response[]>,
mapper: {
paramToId: (param: Param) => string
Expand Down Expand Up @@ -61,7 +62,7 @@ export function generateGetDataFromSquidWithBlockchainFallback<Param, Response>(
}
mergedPosts.push(...dataFromBlockchain)
} catch (e) {
console.error('Error fetching posts from blockchain', e)
console.error(`Error fetching ${dataName} from blockchain`, e)
}

const filteredPosts = mergedPosts.filter((post) => !!post)
Expand Down
3 changes: 3 additions & 0 deletions src/services/api/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { getIdentities, getPosts, getProfiles } from './fetcher'
import { apiInstance } from './utils'

const getPost = poolQuery<string, PostData>({
name: 'getPost',
multiCall: async (postIds) => {
if (postIds.length === 0) return []
return getPosts(postIds)
Expand Down Expand Up @@ -105,6 +106,7 @@ export const getNftQuery = createQuery({
})

const getProfile = poolQuery<string, SubsocialProfile>({
name: 'getProfile',
multiCall: async (addresses) => {
if (addresses.length === 0) return []
return getProfiles(addresses)
Expand All @@ -123,6 +125,7 @@ export const getProfileQuery = createQuery({
})

const getIdentity = poolQuery<string, Identities>({
name: 'getIdentity',
multiCall: async (addresses) => {
if (addresses.length === 0) return []
return getIdentities(addresses)
Expand Down
1 change: 1 addition & 0 deletions src/services/chainsInfo/query.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export const useGetChainDataByNetwork = (network: string) => {
}

const getChainsInfoCall = poolQuery<string, ChainInfo>({
name: 'getChainsInfo',
multiCall: async () => {
const result = await getChainsInfo()

Expand Down
1 change: 1 addition & 0 deletions src/services/contentStaking/backerInfo/query.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ const getBackerInfo = poolQuery<
Params,
{ account: string; info: Record<string, BackerInfo> }
>({
name: 'getBackerInfo',
multiCall: async (params) => {
const resultPromise = params.map(async ({ account, spaceIds }) => {
const result = await getBackerInfoRequest(account, spaceIds)
Expand Down
1 change: 1 addition & 0 deletions src/services/contentStaking/backerLedger/query.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export async function getBackerLedgerRequest(account: string) {
}

const getBackerLedger = poolQuery<string, BackerLedger>({
name: 'getBackerLedger',
multiCall: async (account) => {
const resultPromise = account.map(async (account) => {
const result = await getBackerLedgerRequest(account)
Expand Down
1 change: 1 addition & 0 deletions src/services/contentStaking/backerRewards/query.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ type Params = {
}

const getBackerRewards = poolQuery<Params, RewardsData>({
name: 'getBackerRewards',
multiCall: async (params) => {
const resultPromise = params.map(async ({ account, spaceIds }) => {
const result = await getBackerRewardsRequest(account, spaceIds)
Expand Down
1 change: 1 addition & 0 deletions src/services/contentStaking/creatorsList/query.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export async function getCreatorsListRequest() {
}

const getCreatorsList = poolQuery<string, RegisteredCreator[]>({
name: 'getCreatorsList',
multiCall: async () => {
const result = await getCreatorsListRequest()

Expand Down
1 change: 1 addition & 0 deletions src/services/contentStaking/eraStake/query.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export async function getEraStakeRequest(era: string, spaceIds: string[]) {
}

const getBackerRewards = poolQuery<string, EraStake>({
name: 'getBackerRewards',
multiCall: async (spaceIds) => {
const { data } = getGeneralEraInfoData()

Expand Down
1 change: 1 addition & 0 deletions src/services/contentStaking/generalErainfo/query.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export async function getGeneralEraInfoRequest() {
}

const getGeneralEraInfo = poolQuery<string, GeneralEraInfo>({
name: 'getGeneralEraInfo',
multiCall: async () => {
const result = await getGeneralEraInfoRequest()

Expand Down
1 change: 1 addition & 0 deletions src/services/contentStaking/stakingConsts/query.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export async function getStakingConstsRequest() {
}

const getStakingConsts = poolQuery<string, StakingConsts>({
name: 'getStakingConsts',
multiCall: async () => {
const result = await getStakingConstsRequest()

Expand Down
4 changes: 4 additions & 0 deletions src/services/datahub/content-staking/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ type SuperLikeCount = {
count: number
}
const getSuperLikeCounts = poolQuery<string, SuperLikeCount>({
name: 'getSuperLikeCounts',
multiCall: async (postIds) => {
const res = await datahubQueryRequest<
GetSuperLikeCountsQuery,
Expand Down Expand Up @@ -84,6 +85,7 @@ const getAddressLikeCountToPosts = poolQuery<
{ postId: string; address: string },
AddressLikeCountToPost
>({
name: 'getAddressLikeCountToPosts',
multiCall: async (params) => {
if (!params.length) return []
const addressesToPostIdsMap = new Map<string, string[]>()
Expand Down Expand Up @@ -149,6 +151,7 @@ export type CanPostSuperLiked = {
isExist: boolean
}
const getCanPostsSuperLiked = poolQuery<string, CanPostSuperLiked>({
name: 'getCanPostsSuperLiked',
multiCall: async (postIds) => {
const res = await datahubQueryRequest<
GetCanPostsSuperLikedQuery,
Expand Down Expand Up @@ -235,6 +238,7 @@ export type PostRewards = {
}
}
const getPostRewards = poolQuery<string, PostRewards>({
name: 'getPostRewards',
multiCall: async (postIds) => {
const res = await datahubQueryRequest<
GetPostRewardsQuery,
Expand Down
1 change: 1 addition & 0 deletions src/services/datahub/generalStats/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ type GeneralStats = {
creatorsEarnedTotal: string
}
const getGeneralStats = poolQuery<string, GeneralStats>({
name: 'getGeneralStats',
multiCall: async () => {
const res = await datahubQueryRequest<
{
Expand Down
1 change: 1 addition & 0 deletions src/services/datahub/moderation/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ const pooledGetBlockedResource = poolQuery<
type: 'spaceId' | 'postEntityId' | 'appId'
}
>({
name: 'pooledGetBlockedResource',
multiCall: async (params) => {
if (!params.length) return []
const spaceIds: string[] = []
Expand Down
2 changes: 2 additions & 0 deletions src/services/datahub/posts/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,7 @@ const getPostMetadata = poolQuery<
string,
{ lastCommentId: string; totalCommentsCount: number; postId: string }
>({
name: 'getPostMetadata',
multiCall: async (data) => {
const res = await datahubQueryRequest<
GetPostMetadataQuery,
Expand Down Expand Up @@ -289,6 +290,7 @@ const getUnreadCount = poolQuery<
{ chatId: string; lastRead: { postId?: string; timestamp?: number } },
number
>({
name: 'getUnreadCount',
multiCall: async (data) => {
const pairs = await Promise.all(
data.map(async ({ chatId, lastRead }) => {
Expand Down
1 change: 1 addition & 0 deletions src/services/subsocial/commentIds/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ const getMessagesCountAfterTime = poolQuery<
{ chatId: string; time: number },
{ chatId: string; totalCount: number }
>({
name: 'getMessagesCountAfterTime',
multiCall: async (params) => {
if (!params.length) return []
const queries: { query: string; chatId: string }[] = []
Expand Down
1 change: 1 addition & 0 deletions src/services/subsocial/evmAddresses/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export async function getAccountsData(addresses: string[]) {
}

const getAccountData = poolQuery<string, AccountData>({
name: 'getAccountData',
multiCall: async (addresses) => {
const filteredAddresses = addresses.filter(Boolean)
if (filteredAddresses.length === 0) return []
Expand Down
1 change: 1 addition & 0 deletions src/services/subsocial/posts/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ const getPostIdsBySpaceId = poolQuery<
SubsocialQueryData<string>,
{ spaceId: string; postIds: string[] }
>({
name: 'getPostIdsBySpaceId',
multiCall: async (allParams) => {
if (allParams.length === 0) return []
const [{ api }] = allParams
Expand Down
Loading

0 comments on commit 4849d64

Please sign in to comment.