-
Notifications
You must be signed in to change notification settings - Fork 0
/
afterAuth.js
76 lines (69 loc) · 1.91 KB
/
afterAuth.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
import prisma from "../lib/prisma.js";
import Mantle from "../mantle/mantle.js";
import shopify from "../shopify.js";
export default async function afterAuth(req, res, next) {
const session = res.locals.shopify.session;
if (session && session.shop && session.accessToken) {
let existingShop = await prisma.shop.findFirst({
where: {
myshopifyDomain: session.shop,
},
});
const SHOP_QUERY = `
query {
shop {
id
email
name
}
}
`;
const shopifyClient = new shopify.api.clients.Graphql({ session });
const shopifyResponse = await shopifyClient.query({
data: {
query: SHOP_QUERY,
},
});
const id = shopifyResponse.body.data.shop.id;
const email = shopifyResponse.body.data.shop.email;
const name = shopifyResponse.body.data.shop.name;
const mantleClient = new Mantle({
appId: process.env.MANTLE_APP_ID,
appApiKey: process.env.MANTLE_APP_API_KEY,
});
const mantleResponse = await mantleClient.identifyCustomer({
platform: "shopify",
accessToken: session.accessToken,
platformId: id,
myshopifyDomain: session.shop,
email,
name,
});
if (!existingShop) {
existingShop = await prisma.shop.create({
data: {
myshopifyDomain: session.shop,
accessToken: session.accessToken,
mantleApiToken: mantleResponse.apiToken,
name,
email,
},
});
console.log("created new shop: ", existingShop);
} else {
existingShop = await prisma.shop.update({
where: {
id: existingShop.id,
},
data: {
accessToken: session.accessToken,
mantleApiToken: mantleResponse.apiToken,
name,
email,
},
});
console.log("updated existing shop: ", existingShop);
}
}
next();
}