cache user's metdata in db

This commit is contained in:
Ren Amamiya
2023-07-05 17:19:49 +07:00
parent ec9b54cb82
commit c5ba98e37a
6 changed files with 59 additions and 49 deletions

View File

@@ -1,6 +1,8 @@
import { useQuery } from '@tanstack/react-query';
import { useContext } from 'react';
import { createMetadata, getUserMetadata } from '@libs/storage';
import { RelayContext } from '@shared/relayProvider';
export function useProfile(pubkey: string, fallback?: string) {
@@ -13,14 +15,21 @@ export function useProfile(pubkey: string, fallback?: string) {
} = useQuery(
['user', pubkey],
async () => {
if (fallback) {
if (!fallback) {
const current = Math.floor(Date.now() / 1000);
const cache = await getUserMetadata(pubkey);
if (cache && parseInt(cache.created_at) + 86400 >= current) {
console.log('use cache', cache);
return cache;
} else {
const user = ndk.getUser({ hexpubkey: pubkey });
await user.fetchProfile();
await createMetadata(pubkey, pubkey, JSON.stringify(user.profile));
return user.profile;
}
} else {
const profile = JSON.parse(fallback);
return profile;
} else {
const user = ndk.getUser({ hexpubkey: pubkey });
await user.fetchProfile();
return user.profile;
}
},
{