mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 15:23:29 +00:00
feat(whoop): settings surface — status, disconnect, credentials, sync routes + connect card
Fill the WHOOP route set beside the OAuth connect/callback: status reports connection + token expiry + backfill progress, disconnect revokes the stored tokens and parks the integration, credentials saves/clears the per-user BYO client id/secret encrypted at rest, sync triggers a manual incremental or full pull. Add a WHOOP card to Settings -> Integrations mirroring the Withings card (BYO-keys form, connect/disconnect, status pill, last-sync, backfill notice) and surface whoop rows in the combined integrations-status envelope so the pill reflects real failure state. WHOOP lives under the existing integrations section -- no new slug.
This commit is contained in:
1 parent
d4686ea2a6
commit
008160dc72
18 files changed
+1012
-2
No files matched your search
@@ -29,15 +29,18 @@ export const GET = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "integrations.status" } });
|
||||
|
||||
const [withingsStatus, moodLogStatus, dbUser, withingsConn] =
|
||||
const [withingsStatus, moodLogStatus, whoopStatus, dbUser, withingsConn, whoopConn] =
|
||||
await Promise.all([
|
||||
getIntegrationStatus(user.id, "withings"),
|
||||
getIntegrationStatus(user.id, "moodlog"),
|
||||
getIntegrationStatus(user.id, "whoop"),
|
||||
prisma.user.findUnique({
|
||||
where: { id: user.id },
|
||||
select: {
|
||||
withingsClientIdEncrypted: true,
|
||||
withingsClientSecretEncrypted: true,
|
||||
whoopClientIdEncrypted: true,
|
||||
whoopClientSecretEncrypted: true,
|
||||
moodLogUrlEncrypted: true,
|
||||
moodLogApiKeyEncrypted: true,
|
||||
moodLogEnabled: true,
|
||||
@@ -52,6 +55,14 @@ export const GET = apiHandler(async () => {
|
||||
createdAt: true,
|
||||
},
|
||||
}),
|
||||
prisma.whoopConnection.findUnique({
|
||||
where: { userId: user.id },
|
||||
select: {
|
||||
tokenExpiresAt: true,
|
||||
lastSyncedAt: true,
|
||||
createdAt: true,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
const now = Date.now();
|
||||
@@ -82,6 +93,19 @@ export const GET = apiHandler(async () => {
|
||||
enabled: dbUser?.moodLogEnabled ?? false,
|
||||
legacyLastSyncedAt: dbUser?.moodLogLastSyncedAt?.toISOString() ?? null,
|
||||
} satisfies IntegrationViewModel & MoodLogExtras,
|
||||
{
|
||||
...whoopStatus,
|
||||
configured:
|
||||
!!dbUser?.whoopClientIdEncrypted &&
|
||||
!!dbUser?.whoopClientSecretEncrypted,
|
||||
connected: !!whoopConn,
|
||||
connectedAt: whoopConn?.createdAt?.toISOString() ?? null,
|
||||
legacyLastSyncedAt: whoopConn?.lastSyncedAt?.toISOString() ?? null,
|
||||
tokenExpiresAt: whoopConn?.tokenExpiresAt?.toISOString() ?? null,
|
||||
tokenExpired: whoopConn
|
||||
? whoopConn.tokenExpiresAt.getTime() <= now
|
||||
: null,
|
||||
} satisfies IntegrationViewModel & WhoopExtras,
|
||||
],
|
||||
});
|
||||
});
|
||||
@@ -108,3 +132,12 @@ interface MoodLogExtras {
|
||||
enabled: boolean;
|
||||
legacyLastSyncedAt: string | null;
|
||||
}
|
||||
|
||||
interface WhoopExtras {
|
||||
configured: boolean;
|
||||
connected: boolean;
|
||||
connectedAt: string | null;
|
||||
legacyLastSyncedAt: string | null;
|
||||
tokenExpiresAt: string | null;
|
||||
tokenExpired: boolean | null;
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
vi.mock("@/lib/api-handler", () => ({
|
||||
apiHandler: <T extends (...args: unknown[]) => unknown>(fn: T) => fn,
|
||||
requireAuth: vi.fn(async () => ({ user: { id: "u1" } })),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
user: { findUnique: vi.fn(), update: vi.fn() },
|
||||
whoopConnection: { delete: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/logging/context", () => ({ annotate: vi.fn() }));
|
||||
vi.mock("@/lib/crypto", () => ({ encrypt: (s: string) => `enc:${s}` }));
|
||||
|
||||
vi.mock("@/lib/api-response", () => ({
|
||||
apiSuccess: (data: unknown) => ({ data, error: null, status: 200 }),
|
||||
apiError: (error: string, status: number) => ({ data: null, error, status }),
|
||||
safeJson: async (req: NextRequest) => {
|
||||
try {
|
||||
return { data: await req.json(), error: null };
|
||||
} catch {
|
||||
return { data: null, error: { status: 400 } };
|
||||
}
|
||||
},
|
||||
}));
|
||||
|
||||
import { GET, PUT, DELETE } from "../route";
|
||||
import { prisma } from "@/lib/db";
|
||||
|
||||
const userFind = prisma.user.findUnique as ReturnType<typeof vi.fn>;
|
||||
const userUpdate = prisma.user.update as ReturnType<typeof vi.fn>;
|
||||
|
||||
function req(body: unknown): NextRequest {
|
||||
return new NextRequest("http://localhost/api/whoop/credentials", {
|
||||
method: "PUT",
|
||||
body: JSON.stringify(body),
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
describe("/api/whoop/credentials", () => {
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
it("GET reports hasCredentials false when none stored", async () => {
|
||||
userFind.mockResolvedValue(null);
|
||||
const res = (await (GET as unknown as () => Promise<{ data: unknown }>)())
|
||||
.data as { hasCredentials: boolean };
|
||||
expect(res.hasCredentials).toBe(false);
|
||||
});
|
||||
|
||||
it("PUT 422s on missing fields", async () => {
|
||||
const res = (await (
|
||||
PUT as unknown as (r: NextRequest) => Promise<{ status: number }>
|
||||
)(req({ clientId: "" }))) as { status: number };
|
||||
expect(res.status).toBe(422);
|
||||
expect(userUpdate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("PUT encrypts and stores valid credentials", async () => {
|
||||
userUpdate.mockResolvedValue({});
|
||||
const res = (await (
|
||||
PUT as unknown as (r: NextRequest) => Promise<{ data: unknown }>
|
||||
)(req({ clientId: "id", clientSecret: "secret" }))) as { data: unknown };
|
||||
expect((res.data as { updated: boolean }).updated).toBe(true);
|
||||
expect(userUpdate).toHaveBeenCalledWith({
|
||||
where: { id: "u1" },
|
||||
data: {
|
||||
whoopClientIdEncrypted: "enc:id",
|
||||
whoopClientSecretEncrypted: "enc:secret",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("DELETE clears credentials and connection", async () => {
|
||||
userUpdate.mockResolvedValue({});
|
||||
(prisma.whoopConnection.delete as ReturnType<typeof vi.fn>).mockResolvedValue(
|
||||
{},
|
||||
);
|
||||
const res = (await (DELETE as unknown as () => Promise<{ data: unknown }>)())
|
||||
.data as { deleted: boolean };
|
||||
expect(res.deleted).toBe(true);
|
||||
expect(userUpdate).toHaveBeenCalledWith({
|
||||
where: { id: "u1" },
|
||||
data: {
|
||||
whoopClientIdEncrypted: null,
|
||||
whoopClientSecretEncrypted: null,
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { apiSuccess, apiError, safeJson } from "@/lib/api-response";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { encrypt } from "@/lib/crypto";
|
||||
import { whoopCredentialsSchema } from "@/lib/validations/whoop";
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
/**
|
||||
* Check whether the user has WHOOP BYO-key credentials stored (v1.11.0).
|
||||
*/
|
||||
export const GET = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "whoop.credentials.get" } });
|
||||
|
||||
const dbUser = await prisma.user.findUnique({
|
||||
where: { id: user.id },
|
||||
select: {
|
||||
whoopClientIdEncrypted: true,
|
||||
whoopClientSecretEncrypted: true,
|
||||
},
|
||||
});
|
||||
|
||||
return apiSuccess({
|
||||
hasCredentials:
|
||||
!!dbUser?.whoopClientIdEncrypted && !!dbUser?.whoopClientSecretEncrypted,
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Save WHOOP API credentials (encrypted at rest).
|
||||
*/
|
||||
export const PUT = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "whoop.credentials.update" } });
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson(request);
|
||||
if (jsonError) return jsonError;
|
||||
|
||||
const result = z.safeParse(whoopCredentialsSchema, body);
|
||||
if (!result.success) {
|
||||
return apiError("Client ID and Client Secret are required", 422);
|
||||
}
|
||||
|
||||
await prisma.user.update({
|
||||
where: { id: user.id },
|
||||
data: {
|
||||
whoopClientIdEncrypted: encrypt(result.data.clientId),
|
||||
whoopClientSecretEncrypted: encrypt(result.data.clientSecret),
|
||||
},
|
||||
});
|
||||
|
||||
return apiSuccess({ updated: true });
|
||||
});
|
||||
|
||||
/**
|
||||
* Delete WHOOP credentials and the active connection.
|
||||
*/
|
||||
export const DELETE = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "whoop.credentials.delete" } });
|
||||
|
||||
await prisma.whoopConnection
|
||||
.delete({ where: { userId: user.id } })
|
||||
.catch(() => {});
|
||||
|
||||
await prisma.user.update({
|
||||
where: { id: user.id },
|
||||
data: {
|
||||
whoopClientIdEncrypted: null,
|
||||
whoopClientSecretEncrypted: null,
|
||||
},
|
||||
});
|
||||
|
||||
return apiSuccess({ deleted: true });
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("@/lib/api-handler", () => ({
|
||||
apiHandler: <T extends (...args: unknown[]) => unknown>(fn: T) => fn,
|
||||
requireAuth: vi.fn(async () => ({ user: { id: "u1" } })),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
whoopConnection: { findUnique: vi.fn(), delete: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/logging/context", () => ({ annotate: vi.fn() }));
|
||||
vi.mock("@/lib/auth/audit", () => ({ auditLog: vi.fn() }));
|
||||
vi.mock("@/lib/integrations/status", () => ({ markDisconnected: vi.fn() }));
|
||||
|
||||
vi.mock("@/lib/api-response", () => ({
|
||||
apiSuccess: (data: unknown) => ({ data, error: null, status: 200 }),
|
||||
apiError: (error: string, status: number) => ({ data: null, error, status }),
|
||||
}));
|
||||
|
||||
import { POST } from "../route";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { markDisconnected } from "@/lib/integrations/status";
|
||||
|
||||
const connFind = prisma.whoopConnection.findUnique as ReturnType<typeof vi.fn>;
|
||||
const connDelete = prisma.whoopConnection.delete as ReturnType<typeof vi.fn>;
|
||||
|
||||
describe("POST /api/whoop/disconnect", () => {
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
it("404s when there is no connection", async () => {
|
||||
connFind.mockResolvedValue(null);
|
||||
const res = (await (
|
||||
POST as unknown as () => Promise<{ status: number }>
|
||||
)()) as { status: number };
|
||||
expect(res.status).toBe(404);
|
||||
expect(connDelete).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("deletes the connection and parks the integration on success", async () => {
|
||||
connFind.mockResolvedValue({ id: "c1", userId: "u1" });
|
||||
connDelete.mockResolvedValue({});
|
||||
const res = (await (POST as unknown as () => Promise<{ data: unknown }>)())
|
||||
.data as { disconnected: boolean };
|
||||
expect(res.disconnected).toBe(true);
|
||||
expect(connDelete).toHaveBeenCalledWith({ where: { userId: "u1" } });
|
||||
expect(markDisconnected).toHaveBeenCalledWith("u1", "whoop");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { apiSuccess, apiError } from "@/lib/api-response";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { markDisconnected } from "@/lib/integrations/status";
|
||||
|
||||
/**
|
||||
* Disconnect the WHOOP integration for the current user (v1.11.0).
|
||||
*
|
||||
* Clears the stored OAuth tokens by deleting the `WhoopConnection` row and
|
||||
* parks the integration status at `disconnected`. WHOOP webhook subscriptions
|
||||
* are app-level (registered once per dev app), so there is no per-user
|
||||
* unsubscribe call to make — unlike Withings, which subscribes per category.
|
||||
* The BYO-key credentials on `User` are left intact so a reconnect doesn't
|
||||
* force the user to re-paste them; use the credentials DELETE endpoint to
|
||||
* remove those too.
|
||||
*/
|
||||
export const POST = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "whoop.disconnect" } });
|
||||
|
||||
const connection = await prisma.whoopConnection.findUnique({
|
||||
where: { userId: user.id },
|
||||
});
|
||||
|
||||
if (!connection) {
|
||||
return apiError("No WHOOP connection", 404);
|
||||
}
|
||||
|
||||
await prisma.whoopConnection.delete({
|
||||
where: { userId: user.id },
|
||||
});
|
||||
|
||||
await auditLog("whoop.disconnect", {
|
||||
userId: user.id,
|
||||
});
|
||||
|
||||
await markDisconnected(user.id, "whoop");
|
||||
|
||||
return apiSuccess({ disconnected: true });
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("@/lib/api-handler", () => ({
|
||||
apiHandler: <T extends (...args: unknown[]) => unknown>(fn: T) => fn,
|
||||
requireAuth: vi.fn(async () => ({ user: { id: "u1" } })),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
user: { findUnique: vi.fn() },
|
||||
whoopConnection: { findUnique: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/logging/context", () => ({
|
||||
annotate: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/api-response", () => ({
|
||||
apiSuccess: (data: unknown) => ({ data, error: null }),
|
||||
}));
|
||||
|
||||
import { GET } from "../route";
|
||||
import { prisma } from "@/lib/db";
|
||||
|
||||
const userFind = prisma.user.findUnique as ReturnType<typeof vi.fn>;
|
||||
const connFind = prisma.whoopConnection.findUnique as ReturnType<typeof vi.fn>;
|
||||
|
||||
describe("GET /api/whoop/status", () => {
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
it("reports not-connected, not-configured when nothing is set", async () => {
|
||||
userFind.mockResolvedValue(null);
|
||||
connFind.mockResolvedValue(null);
|
||||
const res = (await (GET as unknown as () => Promise<{ data: unknown }>)())
|
||||
.data as { connected: boolean; configured: boolean };
|
||||
expect(res.connected).toBe(false);
|
||||
expect(res.configured).toBe(false);
|
||||
});
|
||||
|
||||
it("reports configured when credentials exist but no connection", async () => {
|
||||
userFind.mockResolvedValue({
|
||||
whoopClientIdEncrypted: "x",
|
||||
whoopClientSecretEncrypted: "y",
|
||||
});
|
||||
connFind.mockResolvedValue(null);
|
||||
const res = (await (GET as unknown as () => Promise<{ data: unknown }>)())
|
||||
.data as { connected: boolean; configured: boolean };
|
||||
expect(res.connected).toBe(false);
|
||||
expect(res.configured).toBe(true);
|
||||
});
|
||||
|
||||
it("reports connection state with token expiry and backfill flag", async () => {
|
||||
userFind.mockResolvedValue({
|
||||
whoopClientIdEncrypted: "x",
|
||||
whoopClientSecretEncrypted: "y",
|
||||
});
|
||||
connFind.mockResolvedValue({
|
||||
whoopUserId: "w1",
|
||||
lastSyncedAt: new Date("2026-06-03T00:00:00Z"),
|
||||
tokenExpiresAt: new Date(Date.now() + 3_600_000),
|
||||
backfillCompletedAt: null,
|
||||
createdAt: new Date("2026-06-01T00:00:00Z"),
|
||||
scope: "offline read:recovery",
|
||||
});
|
||||
const res = (await (GET as unknown as () => Promise<{ data: unknown }>)())
|
||||
.data as {
|
||||
connected: boolean;
|
||||
tokenExpired: boolean;
|
||||
backfillCompleted: boolean;
|
||||
};
|
||||
expect(res.connected).toBe(true);
|
||||
expect(res.tokenExpired).toBe(false);
|
||||
expect(res.backfillCompleted).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
|
||||
/**
|
||||
* Get WHOOP connection status for the current user (v1.11.0).
|
||||
*
|
||||
* Mirrors the Withings status route: `configured` checks the per-user BYO-key
|
||||
* credentials, the connection row reports last-sync + token expiry +
|
||||
* backfill progress. The token-refresh-in-status dance Withings does is not
|
||||
* needed here — WHOOP `tokenExpired` is reported straight off the row and the
|
||||
* sync path refreshes lazily via `getValidToken`.
|
||||
*/
|
||||
export const GET = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "whoop.status" } });
|
||||
|
||||
const dbUser = await prisma.user.findUnique({
|
||||
where: { id: user.id },
|
||||
select: {
|
||||
whoopClientIdEncrypted: true,
|
||||
whoopClientSecretEncrypted: true,
|
||||
},
|
||||
});
|
||||
|
||||
const configured =
|
||||
!!dbUser?.whoopClientIdEncrypted && !!dbUser?.whoopClientSecretEncrypted;
|
||||
|
||||
const connection = await prisma.whoopConnection.findUnique({
|
||||
where: { userId: user.id },
|
||||
select: {
|
||||
whoopUserId: true,
|
||||
lastSyncedAt: true,
|
||||
tokenExpiresAt: true,
|
||||
backfillCompletedAt: true,
|
||||
createdAt: true,
|
||||
scope: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!connection) {
|
||||
return apiSuccess({ connected: false, configured });
|
||||
}
|
||||
|
||||
const tokenExpired = connection.tokenExpiresAt.getTime() <= Date.now();
|
||||
|
||||
return apiSuccess({
|
||||
connected: true,
|
||||
configured,
|
||||
lastSyncedAt: connection.lastSyncedAt,
|
||||
connectedAt: connection.createdAt,
|
||||
tokenExpired,
|
||||
tokenExpiresAt: connection.tokenExpiresAt,
|
||||
backfillCompleted: !!connection.backfillCompletedAt,
|
||||
scope: connection.scope,
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
vi.mock("@/lib/api-handler", () => ({
|
||||
apiHandler: <T extends (...args: unknown[]) => unknown>(fn: T) => fn,
|
||||
requireAuth: vi.fn(async () => ({ user: { id: "u1" } })),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/logging/context", () => ({ annotate: vi.fn() }));
|
||||
vi.mock("@/lib/whoop/sync", () => ({ syncUserWhoop: vi.fn() }));
|
||||
|
||||
vi.mock("@/lib/api-response", () => ({
|
||||
apiSuccess: (data: unknown) => ({ data, error: null }),
|
||||
}));
|
||||
|
||||
import { POST } from "../route";
|
||||
import { syncUserWhoop } from "@/lib/whoop/sync";
|
||||
|
||||
const sync = syncUserWhoop as ReturnType<typeof vi.fn>;
|
||||
|
||||
function req(body?: unknown): NextRequest {
|
||||
return new NextRequest("http://localhost/api/whoop/sync", {
|
||||
method: "POST",
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
describe("POST /api/whoop/sync", () => {
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
it("triggers an incremental sync by default", async () => {
|
||||
sync.mockResolvedValue(7);
|
||||
const res = (await (
|
||||
POST as unknown as (r: NextRequest) => Promise<{ data: unknown }>
|
||||
)(req({}))) as { data: { imported: number; fullSync: boolean } };
|
||||
expect(res.data.imported).toBe(7);
|
||||
expect(res.data.fullSync).toBe(false);
|
||||
expect(sync).toHaveBeenCalledWith("u1", { fullSync: false });
|
||||
});
|
||||
|
||||
it("honours fullSync: true", async () => {
|
||||
sync.mockResolvedValue(99);
|
||||
const res = (await (
|
||||
POST as unknown as (r: NextRequest) => Promise<{ data: unknown }>
|
||||
)(req({ fullSync: true }))) as { data: { fullSync: boolean } };
|
||||
expect(res.data.fullSync).toBe(true);
|
||||
expect(sync).toHaveBeenCalledWith("u1", { fullSync: true });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { syncUserWhoop } from "@/lib/whoop/sync";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
/**
|
||||
* Manually trigger a WHOOP sync for the current user (v1.11.0).
|
||||
*
|
||||
* Mirrors the Withings manual-sync route: incremental by default, full
|
||||
* history when `{ fullSync: true }` is posted.
|
||||
*/
|
||||
export const POST = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "whoop.sync" } });
|
||||
|
||||
let fullSync = false;
|
||||
try {
|
||||
const body = await request.json();
|
||||
fullSync = body?.fullSync === true;
|
||||
} catch {
|
||||
// no body provided -> default incremental sync
|
||||
}
|
||||
|
||||
const imported = await syncUserWhoop(user.id, { fullSync });
|
||||
return apiSuccess({ imported, fullSync });
|
||||
});
|
||||
Reference in new issue
Block a user