t_wの輪郭

Feedlyでフォローするボタン
Amplify『Amplifyでアクセストークンをin-memoryに置いてみる』

idTokenをぶっこ抜く

InMemoryTokenStorage.ts

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,
    }
})

ぶっこ抜いたidTokenを使ってAPIを叩く

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に置いてみる』

あれ