Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: introduce useSocial and useSocialProfile hooks #22

Open
wants to merge 1 commit into
base: beta
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion jest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const config: Config = {
preset: 'ts-jest',
rootDir: './',
setupFiles: ['<rootDir>/test/setup.ts'],
testEnvironment: 'node',
testEnvironment: 'jest-environment-jsdom',
transform: {
'^.+\\.ts?$': [
'ts-jest',
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
"@semantic-release/git": "^10.0.1",
"@semantic-release/github": "^10.0.3",
"@semantic-release/release-notes-generator": "^13.0.0",
"@testing-library/react-hooks": "^8.0.1",
"@types/jest": "^29.5.12",
"@types/node": "^20.12.8",
"@typescript-eslint/parser": "^7.7.1",
Expand All @@ -62,6 +63,7 @@
"globals": "^15.0.0",
"husky": "^9.0.11",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"lint-staged": "^15.2.2",
"near-sandbox": "0.0.18",
"prettier": "^3.2.5",
Expand Down
40 changes: 40 additions & 0 deletions src/components/SocialProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import * as React from 'react';
import Social from '../controllers/Social';

type SocialContextType = {
social: Social;
};

export const SocialContext = React.createContext<SocialContextType | undefined>(undefined);

type SocialProviderProps = {
children: React.ReactNode;
contractId?: string;
onProvision?: (social: Social) => void;
};

export const SocialProvider = ({
children,
contractId,
onProvision,
}: SocialProviderProps) => {
const [social] = React.useState<Social>(new Social({ contractId }));

React.useEffect(() => {
if (contractId) {
social.setContractId(contractId);
}
}, [contractId, social]);

React.useEffect(() => {
if (onProvision) {
onProvision(social);
}
}, [social, onProvision]);

return (
<SocialContext.Provider value={{ social }}>
{children}
</SocialContext.Provider>
);
};
1 change: 1 addition & 0 deletions src/constants/SocialNearIpfs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const SOCIAL_IPFS_BASE_URL = 'https://ipfs.near.social/ipfs';
1 change: 1 addition & 0 deletions src/constants/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './Fees';
export * from './SocialNearIpfs';
2 changes: 2 additions & 0 deletions src/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './useSocialProfile';
export * from './useSocial';
57 changes: 57 additions & 0 deletions src/hooks/useSocial.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import React from 'react';
import { renderHook } from '@testing-library/react-hooks';
import { SocialProvider } from '../components/SocialProvider';
import { useSocial } from '@app/hooks';
import { Account } from 'near-api-js';
import createEphemeralAccount from '@test/helpers/createEphemeralAccount';

jest.mock('@app/hooks', () => ({

useSocial: jest.fn(() => ({
social: {
async get({ keys }: { keys: string[] }) {
return keys.reduce((acc, key) => {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

.reduce allows you to declare the the type to cast, rather than using the as notation.

keys.reduce<Record<string, unknown>>((acc, key) => {
  acc[key] = { profile: { name: 'TestUser' } };
  return acc;
}, {});

acc[key] = { profile: { name: 'TestUser' } };
return acc;
}, {} as Record<string, any>);

Check failure on line 16 in src/hooks/useSocial.test.tsx

View workflow job for this annotation

GitHub Actions / Lint

Unexpected any. Specify a different type
},
async getVersion() {
return '1.0.0';
},
async set({ data }: { data: Record<string, any> }) {

Check failure on line 21 in src/hooks/useSocial.test.tsx

View workflow job for this annotation

GitHub Actions / Lint

Unexpected any. Specify a different type
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As before, Record<string, unknown> is favoured over using any.

return { data };
},
setContractId(contractId: string) {
return contractId;
},
},
})),
}));

describe('useSocial hook', () => {
let signer: Account;

beforeEach(async () => {
const result = await createEphemeralAccount();
signer = result.account;
});

it('should fetch data using get method', async () => {
const wrapper: React.FC<{ children: React.ReactNode }> = ({ children }) => (
<SocialProvider>
{children}
</SocialProvider>
);

const { result } = renderHook(() => useSocial(), { wrapper });

const { social } = result.current;

let data: any;

Check failure on line 50 in src/hooks/useSocial.test.tsx

View workflow job for this annotation

GitHub Actions / Lint

Unexpected any. Specify a different type
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this will fail the linter. For objects, we can use Record<string, unknown>.

await React.act(async () => {
data = await social.get({ keys: ['unknown.test.near'], signer });
});

expect(data).toEqual({ 'unknown.test.near': { profile: { name: 'TestUser' } } });
});
});
11 changes: 11 additions & 0 deletions src/hooks/useSocial.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { useContext } from 'react';

import { SocialContext } from '../components/SocialProvider';

Check failure on line 3 in src/hooks/useSocial.ts

View workflow job for this annotation

GitHub Actions / Build Package

File '/home/runner/work/near-social-js/near-social-js/src/components/SocialProvider.tsx' is not listed within the file list of project '/home/runner/work/near-social-js/near-social-js/tsconfig.build.json'. Projects must list all files or use an 'include' pattern.

export const useSocial = () => {
const context = useContext(SocialContext);
if (context === undefined) {
throw new Error('useSocial must be used within a SocialProvider');
}
return context;
};
36 changes: 36 additions & 0 deletions src/hooks/useSocialProfile.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import React from 'react';
import { renderHook } from '@testing-library/react-hooks';
import { SocialProvider } from '../components/SocialProvider';
import { useSocialProfile } from '@app/hooks';
import { Account } from 'near-api-js';
import createEphemeralAccount from '@test/helpers/createEphemeralAccount';

jest.mock('@app/hooks', () => ({
useSocialProfile: jest.fn(() => ({
profile: { name: 'TestUser', description: 'Test description' },
profileImageUrl: 'https://example.com/image.jpg',
error: null,
})),
}));

describe('useSocialProfile hook', () => {
let signer: Account;

beforeEach(async () => {
const result = await createEphemeralAccount();
signer = result.account;
});

it('should fetch profile data for a given accountId', async () => {
const wrapper: React.FC<{ children: React.ReactNode }> = ({ children }) => (
<SocialProvider>
{children}
</SocialProvider>
);

const { result } = renderHook(() => useSocialProfile(signer.accountId, signer), { wrapper });
const { profile } = result.current;

expect(profile).toEqual({ name: 'TestUser', description: 'Test description' });
});
});
47 changes: 47 additions & 0 deletions src/hooks/useSocialProfile.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { useEffect, useState } from 'react';
import { useSocial } from './useSocial';
import { SOCIAL_IPFS_BASE_URL } from '../constants';
import { ISocialProfile } from '@app/types';
import { Account } from 'near-api-js';

export const useSocialProfile = (
accountId: string | null | undefined,
signer: Account
) => {
const { social } = useSocial();
const [profile, setProfile] = useState<ISocialProfile | undefined>(undefined);
const [error, setError] = useState<string | null>(null);

const profileImageUrl =
profile?.image?.url ?? profile?.image?.ipfs_cid
? `${SOCIAL_IPFS_BASE_URL}/${profile?.image?.ipfs_cid}`
: undefined;

useEffect(() => {
if (!accountId || !social) return;

const fetchProfile = async () => {
try {
const response = await social.get({
signer,
keys: [`${accountId}/profile/**`],
});

setProfile(
(response[accountId] as { profile?: ISocialProfile })?.profile ?? {}
);
} catch (error) {
console.error(error);
setError('Failed to fetch profile data');
}
};

fetchProfile();
}, [accountId, social, signer]);

return {
profile,
profileImageUrl,
error,
};
};
20 changes: 20 additions & 0 deletions src/types/ISocialProfile.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
interface ISocialProfile {
backgroundImage?: {
ipfs_cid?: string;
url?: string;
};
description?: string;
linktree?: {
github?: string;
twitter?: string;
website?: string;
};
name?: string;
image?: {
ipfs_cid?: string;
url?: string;
};
tags?: Record<string, ''>;
}

export default ISocialProfile;
1 change: 1 addition & 0 deletions src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,4 @@ export type { default as ISocialDBContractStorageBalanceOfArgs } from './ISocial
export type { default as ISocialDBContractStorageDepositArgs } from './ISocialDBContractStorageDepositArgs';
export type { default as ISocialDBContractStorageTracker } from './ISocialDBContractStorageTracker';
export type { default as IStorageBalanceOfOptions } from './IStorageBalanceOfOptions';
export type { default as ISocialProfile } from './ISocialProfile';
2 changes: 2 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"compilerOptions": {
"jsx": "react",
"allowSyntheticDefaultImports": true,
"allowUnreachableCode": false,
"alwaysStrict": true,
Expand All @@ -25,6 +26,7 @@
"@app/enums": ["src/enums"],
"@app/types": ["src/types"],
"@app/utils/*": ["src/utils/*"],
"@app/hooks": ["src/hooks"],
"@test/constants": ["test/constants"],
"@test/credentials/*": ["test/credentials/*"],
"@test/helpers/*": ["test/helpers/*"]
Expand Down
Loading
Loading