Skip to content

Commit

Permalink
fix sync_provider_id flow
Browse files Browse the repository at this point in the history
  • Loading branch information
kibagateaux committed Jan 12, 2024
1 parent e420871 commit 63cfaf9
Show file tree
Hide file tree
Showing 5 changed files with 54 additions and 56 deletions.
42 changes: 21 additions & 21 deletions src/app/inventory/[item].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ interface ItemPageProps {
}

const ItemPage: React.FC<ItemPageProps> = () => {
const { item: id } = useLocalSearchParams();
const { item: id }: { item: string } = useLocalSearchParams();
const { inventory, loading } = useInventory();
const { player, getSpellBook } = useAuth();

Expand All @@ -60,27 +60,14 @@ const ItemPage: React.FC<ItemPageProps> = () => {
);
// console.log('Item: oauth', itemOauthConfig, request, response);

useMemo(async () => {
if (item?.id) {
// configure oauth if required for item equip/unequip
const oauth = oauthConfigs[item.id];
console.log('page:inv:item:oauth', oauth);
if (oauth)
setItemOauth({
...oauth,
state: await generateRedirectState(item.id as OAuthProviderIds),
});

// we cant store item status in config so compute and store in store
if (!status)
item!.checkStatus().then((newStatus: ItemStatus) => {
console.log('pg:Inv:Item check item status', newStatus);
setStatus(newStatus);
});
}
}, [item, status]);

useMemo(() => {
// we cant store item status in config so compute and store in store
if (item?.id && !status)
item!.checkStatus().then((newStatus: ItemStatus) => {
console.log('pg:Inv:Item check item status', newStatus);
setStatus(newStatus);
});

if (item?.abilities?.length && status) {
Promise.all(
item.abilities?.filter(async (ability) => {
Expand All @@ -103,6 +90,19 @@ const ItemPage: React.FC<ItemPageProps> = () => {
}
}, [id, item, inventory]);

useMemo(async () => {
if (item?.id) {
// configure oauth if required for item equip/unequip
const oauth = oauthConfigs[item.id];
console.log('page:inv:item:oauth', oauth);
if (oauth)
setItemOauth({
...oauth,
state: await generateRedirectState(item.id as OAuthProviderIds),
});
}
}, [item]);

if (loading) return <ActivityIndicator animating size="large" />;

if (!inventory) return <Text> Item Not Currently Available For Gameplay </Text>;
Expand Down
7 changes: 0 additions & 7 deletions src/inventory/spotify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,19 +63,12 @@ const item: InventoryItem = {
{ ...IntelligenceStat, value: 5 },
],
checkStatus: async () => {
console.log(
'Inv:Spotify:checkStatus',
await getCached({ slot: ID_PLAYER_SLOT }),
await getCached({ slot: ID_PROVIDER_IDS_SLOT }),
ITEM_ID,
);
const cached = (await getCached<obj>({ slot: ID_PROVIDER_IDS_SLOT }))?.[ITEM_ID];
console.log('Inv:Spotify:checkStatus', cached);

// TODO could make api request to see if access_token exist on API but ID should be saved on equip
// only irrelevant if logging in old account to new device.
return cached ? 'equipped' : 'unequipped';
// return 'equipped';
},
canEquip: async () => true,
equip,
Expand Down
21 changes: 11 additions & 10 deletions src/utils/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,12 @@ import { getSpellBook } from 'utils/zkpid';

// TODO persist cache to local storage for better offline use once internet connection lost?
// https://www.apollographql.com/docs/react/caching/advanced-topics#persisting-the-cache

let client: ApolloClient;
export const getGqlClient = () =>
client
? client
: (client = new ApolloClient({
uri: `${getAppConfig().API_URL}` ?? 'http://localhost:8888/graphql',
uri: `${getAppConfig().API_URL}/graphql`,
cache: new InMemoryCache(),

// optional metadata
Expand Down Expand Up @@ -51,14 +50,16 @@ export const qu =
},
};
console.log('api:qu:(player, vars)', spellbook.address, variables);
console.log("api:qu:verification '", cleaned, "'", majikMsg);
console.log('api:qu:client', getGqlClient());
console.log('api:qu:verification ', `'${cleaned}'`, '---', majikMsg);
console.log('api:qu:qu/mu', !!query, !!mutation);
// console.log("api:qu:req ", await getGqlClient().query({

// getGqlClient().mutate({
// ...baseRequest,
// // fetchPolicy: 'cache-first', // TODO add useCache: boolean to switch between query vs readQuery?
// query: gql`${cleaned}`,
// }));
// // fetchPolicy: 'cache-first', // TODO add useCache: boolean to switch between query vs readQuery?
// mutation: gql`${cleaned}`,
// }).then((req) => console.log("sample qu res", req))
// .catch((err) => console.log("sample qu err", err))

return query
? getGqlClient().query({
...baseRequest,
Expand All @@ -77,7 +78,7 @@ export const qu =
};

export const MU_ACTIVATE_JINNI = `
mutation(
mutation jinni_activate(
$verification: SignedRequest!,
$majik_msg: String!,
$player_id: String!
Expand All @@ -91,7 +92,7 @@ export const MU_ACTIVATE_JINNI = `
`;

export const MU_SUBMIT_DATA = `
mutation(
mutation submit_data(
$verification: SignedRequest!,
$data_provider: DataProvider!,
$data: [RawInputData]!,
Expand Down
2 changes: 1 addition & 1 deletion src/utils/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ type AppConfig = {

export const getAppConfig = (): AppConfig => ({
NODE_ENV: process.env.NODE_ENV || 'development',
API_URL: process.env.EXPO_PUBLIC_API_URL || 'http://localhost:3000',
API_URL: process.env.EXPO_PUBLIC_API_URL || 'http://localhost:8888',
API_KEY: process.env.EXPO_PUBLIC_API_KEY || 'test-api-key',

ETH_NETWORK: process.env.EXPO_PUBLIC_ETH_NETWORK || 'optimism',
Expand Down
38 changes: 21 additions & 17 deletions src/utils/oauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { OAuthProvider, OAuthProviderIds } from 'types/GameMechanics';
import {
ID_OAUTH_NONCE_SLOT,
ID_PLAYER_SLOT,
ID_PROVIDER_TEMPLATE_SLOT,
ID_PROVIDER_IDS_SLOT,
getAppConfig,
getCached,
saveStorage,
Expand Down Expand Up @@ -112,18 +112,16 @@ export const generateRedirectState = async (provider: OAuthProviderIds): Promise
};

export const QU_PROVIDER_ID = cleanGql(`
mutation(
$verification: SignedRequest!,
mutation sync_provider_id(
$verification: SignedRequest,
$provider: String!,
$playerId: String!
$player_id: String!
) {
sync_provider_id(
verification: $verification,
provider: $provider,
player_id: $playerId
) {
id
}
player_id: $player_id
)
}
`);

Expand All @@ -135,16 +133,22 @@ export const QU_PROVIDER_ID = cleanGql(`
* @param provider - provider that issues id
* @returns id on provider or null
*/
const quProviderId = qu({ mutation: QU_PROVIDER_ID });
export const getProviderId = async ({ playerId, provider }: obj): Promise<string | null> => {
const cached = (await getCached<obj>({ slot: ID_PROVIDER_TEMPLATE_SLOT }))?.[provider];
const cached = (await getCached<obj>({ slot: ID_PROVIDER_IDS_SLOT }))?.[provider];
console.log('util:oauth:getProviderId:cached', cached);
if (cached) return cached;
const response = await qu({ mutation: QU_PROVIDER_ID })({ playerId, provider });
console.log('util:oauth:getProviderId:res', response);
const id = response?.data ? response.data.id : null;
console.log('util:oauth:getProviderId', response, id);
id &&
playerId === (await getCached<string>({ slot: ID_PLAYER_SLOT })) &&
(await saveStorage(ID_PROVIDER_TEMPLATE_SLOT, { [provider]: id }, true));
return id;
try {
const response = await quProviderId({ player_id: playerId, provider });
console.log('util:oauth:getProviderId:res', response.data);
const id = response?.data ? response.data.sync_provider_id : null;
console.log('util:oauth:getProviderId', response, id);
id &&
playerId === (await getCached<string>({ slot: ID_PLAYER_SLOT })) &&
(await saveStorage(ID_PROVIDER_IDS_SLOT, { [provider]: id }, true));
return id;
} catch (e) {
console.log('util:oauth:getProviderId:ERROR', e);
return null;
}
};

0 comments on commit 63cfaf9

Please sign in to comment.