https://zenn.dev/p0n/articles/b383c33faae4e3
『Amplifyでアクセストークンをin-memoryに置いてみる』
2023/12/3 16:01:00
export class InMemoryTokenStorage implements Storage {
private storage: { [key: string]: string | null } = {}
get length(): number {
return Object.keys(this.storage).length
}
key(index: number): string | null {
return Object.keys(this.storage)[index]
}
getItem(key: string): string | null {
return this.storage[key]
}
setItem(key: string, value: string): void {
this.storage[key] = value
}
removeItem(key: string): void {
delete this.storage[key]
}
clear(): void {
this.storage = {}
}
}
const token_storage = new InMemoryTokenStorage();
Amplify.configure({
...awsmobile,
Auth: {
storage: token_storage,
}
})
async function idToken_get() {
(await public_user_account_get());
return Object.entries(token_storage.storage).map(([key, value]) => `${key}=${value}`).join("; ");
}
async function public_user_account_get() {
return await (async () => {
try {
return await Auth.currentAuthenticatedUser();
} catch (error) {
try {
return await Auth.signIn(process.env.PUBLIC_EMAIL_ADDRESS ?? "", process.env.PUBLIC_PASSWORD ?? "");
} catch (error) {
return undefined;
}
}
})()
}
const SSR = withSSRContext({ req: { headers: { cookie: await idToken_get() } } });
const result = await SSR.API.graphql({
query: deleteRelation,
variables: {
input: {
id: relation.id,
_version: relation._version,
}
}
})
InMemoryTokenStorageのパクリ元:『Amplifyでアクセストークンをin-memoryに置いてみる』