calcom/packages/app-store/vital/api/token.ts
alannnc 8c9096b55b
Vital App - Auto reschedule based on health data (#2500)
* Add vital integration

* Tidy up client_user_id creation

* Rename vital app to vitalother to follow name rules

* Added env var

* App vital reschedule

* Fix on app structure and api calls

* Implemented user identification from webhook

* WIP fix api call and read me

* Save vital settings via api

* Now saving userVitalSettings and trigger reschedule on selected param

* Added translations

* Fix type for vitalSettings

* Using api to get env vars required for url, fix display of vital settings

* Fix hours placeholder, translation not working

* Renames vital app

* Update seed-app-store.ts

* Update package.json

* Update yarn.lock

* Refactored env variables

* Update README.md

* Migrates to api_keys

* Extracts AppConfiguration

* vitalClient fixes

* Update index.ts

* Update metadata.ts

* Update index.ts

* Update metadata.ts

* Added namespace vital for translations

Co-authored-by: Maitham <maithamdib@gmail.com>
Co-authored-by: zomars <zomars@me.com>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-05-06 17:21:30 +00:00

57 lines
1.7 KiB
TypeScript

import { Prisma } from "@prisma/client";
import type { NextApiRequest, NextApiResponse } from "next";
import { WEBAPP_URL } from "@calcom/lib/constants";
import prisma from "@calcom/prisma";
import { initVitalClient, vitalEnv } from "../lib/client";
/**
* This is will generate a user token for a client_user_id`
* @param req
* @param res
*/
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
// Get user id
const calcomUserId = req.session?.user?.id;
if (!calcomUserId) {
return res.status(401).json({ message: "You must be logged in to do this" });
}
const vitalClient = await initVitalClient();
if (!vitalClient || !vitalEnv)
return res.status(400).json({ message: "Missing vital client, try calling `initVitalClient`" });
// Create a user on vital
let userVital;
try {
userVital = await vitalClient.User.create(`cal_${calcomUserId}`);
} catch (e) {
userVital = await vitalClient.User.resolve(`cal_${calcomUserId}`);
}
try {
if (userVital?.user_id) {
await prisma.credential.create({
data: {
type: "vital_other",
key: { userVitalId: userVital.user_id } as unknown as Prisma.InputJsonObject,
userId: calcomUserId,
appId: "vital-automation",
},
});
}
const token = await vitalClient.Link.create(
userVital?.user_id,
undefined,
WEBAPP_URL + "/api/integrations/vital/callback"
);
return res.status(200).json({
token: token.link_token,
url: `https://link.tryvital.io/?env=${vitalEnv.mode}&region=${vitalEnv.region}`,
});
} catch (e) {
return res.status(400).json({ error: JSON.stringify(e) });
}
}