-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcognito-id-with-apollo.js
81 lines (67 loc) · 1.85 KB
/
cognito-id-with-apollo.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
const { CognitoUser, AuthenticationDetails, CognitoUserPool } = require('amazon-cognito-identity-js');
const { ApolloClient, InMemoryCache, createHttpLink, gql } = require('@apollo/client/core');
const poolData = {
UserPoolId: '',
ClientId: ''
};
const userPool = new CognitoUserPool(poolData);
function signIn(username, password) {
return new Promise((resolve, reject) => {
const authenticationDetails = new AuthenticationDetails({
Username: username,
Password: password,
});
const cognitoUser = new CognitoUser({
Username: username,
Pool: userPool,
});
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: (session) => {
resolve(session.getIdToken().getJwtToken());
},
onFailure: (err) => {
reject(err);
},
});
});
}
const httpLink = createHttpLink({
uri: '', // gql endpoint
});
const client = new ApolloClient({
link: httpLink,
cache: new InMemoryCache(),
});
const QUERY = gql`
query SampleQuery {
getItems(userId: "12") {
itemName
itemId
}
}
`;
async function fetchAppSyncData(token) {
try {
const result = await client.query({
query: QUERY,
context: {
headers: {
Authorization: token
}
}
});
return result.data;
} catch (error) {
console.error("Error fetching data:", error);
throw error;
}
}
async function main() {
const username = '';
const password = '';
const token = await signIn(username, password);
console.log("Cognito Token:", token);
const data = await fetchAppSyncData(token);
console.log(JSON.stringify(data, null, 2));
}
main();