Skip to content

Commit

Permalink
feat: support page author
Browse files Browse the repository at this point in the history
  • Loading branch information
devrsi0n committed Apr 17, 2024
1 parent 252b210 commit 92a1952
Show file tree
Hide file tree
Showing 22 changed files with 389 additions and 100 deletions.
21 changes: 18 additions & 3 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,25 @@
"configurations": [
{
"name": "Next.js: debug server-side",
"type": "node-terminal",
"type": "node",
"request": "launch",
"command": "npm run debug",
"cwd": "${workspaceFolder}/apps/main"
"runtimeExecutable": "${workspaceFolder}/node_modules/next/dist/bin/next",
"env": {
"NODE_OPTIONS": "--inspect"
},
"cwd": "${workspaceFolder}/apps/main",
"sourceMapPathOverrides": {
"webpack:///./*": "${workspaceRoot}/apps/main/*"
},
"console": "integratedTerminal",

// Files to exclude from debugger (e.g. call stack)
"skipFiles": [
// Node.js internal core modules
"<node_internals>/**",
// Ignore all dependencies (optional)
"${workspaceFolder}/apps/main/node_modules/**"
]
},
{
"type": "node",
Expand Down
33 changes: 33 additions & 0 deletions apps/main/src/pages/api/sdk/page.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { prisma } from '@chirpy-dev/trpc';
import type { NextApiRequest, NextApiResponse } from 'next';

import { getAPIHandler } from '$/server/common/api-handler';

const handler = getAPIHandler();
handler.get(getPage);

export default handler;

async function getPage(req: NextApiRequest, res: NextApiResponse) {
const auth = req.headers.authorization;
const apiKey = auth?.split(' ')[1];
if (!auth || !apiKey) {
res.status(401).end('Unauthorized, missing API key');
return;
}
const setting = await prisma.settings.findUnique({
where: {
sdkKey: apiKey,
},
});
if (!setting) {
res.status(401).end('Unauthorized, invalid API key');
return;
}
const page = await prisma.page.findUnique({
where: {
url: req.query.url as string,
},
});
res.status(200).json(page);
}
47 changes: 47 additions & 0 deletions apps/main/src/pages/api/sdk/page/link-author.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { prisma } from '@chirpy-dev/trpc';
import type { NextApiRequest, NextApiResponse } from 'next';
import { z } from 'zod';

import { getAPIHandler } from '$/server/common/api-handler';

const handler = getAPIHandler();
handler.post(linkAuthor);

export default handler;

const SCHEMA = z.object({
pageUrl: z.string().url(),
authorId: z.string(),
});

async function linkAuthor(req: NextApiRequest, res: NextApiResponse) {
const auth = req.headers.authorization;
const apiKey = auth?.split(' ')[1];
if (!auth || !apiKey) {
res.status(401).end('Unauthorized, missing API key');
return;
}
const setting = await prisma.settings.findUnique({
where: {
sdkKey: apiKey,
},
});
if (!setting) {
res.status(401).end('Unauthorized, invalid API key');
return;
}
const result = SCHEMA.safeParse(JSON.parse(req.body));
if (!result.success) {
res.status(400).end('Bad request, expect pageURL and authorId');
return;
}
await prisma.page.update({
where: {
url: result.data.pageUrl,
},
data: {
authorId: result.data.authorId,
},
});
res.status(200).end('ok');
}
40 changes: 27 additions & 13 deletions apps/main/src/pages/api/sdk/project.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { prisma } from '@chirpy-dev/trpc';
import type { NextApiRequest, NextApiResponse } from 'next';
import { z } from 'zod';

import { getAPIHandler } from '$/server/common/api-handler';

Expand Down Expand Up @@ -46,18 +47,19 @@ async function getProject(req: NextApiRequest, res: NextApiResponse) {
res.status(200).json(setting.user.projects[0] || null);
}

const SCHEMA = z.object({
domain: z.string(),
name: z.string(),
});

async function createProject(req: NextApiRequest, res: NextApiResponse) {
const auth = req.headers.authorization;
const apiKey = auth?.split(' ')[1];
if (!auth || !apiKey) {
res.status(401).end('Unauthorized, missing API key');
return;
}
const domain = req.query.domain as string;
if (!domain) {
res.status(400).end('Bad request, missing domain');
return;
}

const setting = await prisma.settings.findUnique({
where: {
sdkKey: apiKey,
Expand Down Expand Up @@ -87,14 +89,26 @@ async function createProject(req: NextApiRequest, res: NextApiResponse) {
.end('Forbidden, too many projects. Please upgrade to Enterprise plan');
return;
}
const proj = await prisma.project.create({
data: {
name: req.query.name as string,
domain,
userId: setting.user.id,
},
});
res.status(200).json(proj);
const result = SCHEMA.safeParse(JSON.parse(req.body));
if (!result.success) {
res.status(400).end(`Bad request, ${result.error}`);
return;
}
try {
const proj = await prisma.project.create({
data: {
name: result.data.name,
domain: result.data.domain,
userId: setting.user.id,
},
});
res.status(200).json(proj);
} catch (error) {
console.error('create project failed', error);
res
.status(400)
.end(`Bad request, create project failed, double check your input`);
}
}

async function deleteProject(req: NextApiRequest, res: NextApiResponse) {
Expand Down
52 changes: 52 additions & 0 deletions apps/main/src/pages/api/sdk/user.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { prisma } from '@chirpy-dev/trpc';
import type { NextApiRequest, NextApiResponse } from 'next';
import { z } from 'zod';

import { getAPIHandler } from '$/server/common/api-handler';

const handler = getAPIHandler();
handler.post(createUser);

export default handler;

const schema = z.object({
email: z.string().email(),
name: z.string(),
});

async function createUser(req: NextApiRequest, res: NextApiResponse) {
const auth = req.headers.authorization;
const apiKey = auth?.split(' ')[1];
if (!auth || !apiKey) {
res.status(401).end('Unauthorized, missing API key');
return;
}
const setting = await prisma.settings.findUnique({
where: {
sdkKey: apiKey,
},
});
if (!setting) {
res.status(401).end('Unauthorized, invalid API key');
return;
}
const result = schema.safeParse(JSON.parse(req.body));
if (!result.success) {
res.status(400).end(`Bad request, ${result.error}`);
return;
}
try {
const user = await prisma.user.create({
data: {
email: result.data.email,
name: result.data.name,
},
});
res.status(200).json(user);
} catch (error) {
console.error('create user failed', error);
res
.status(400)
.end(`Bad request, create user failed, double check your input`);
}
}
58 changes: 25 additions & 33 deletions apps/main/src/pages/widget/comment/[pageURL].tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
import { prisma, ssg } from '@chirpy-dev/trpc';
import { CommonWidgetProps, Theme } from '@chirpy-dev/types';
import { Theme } from '@chirpy-dev/types';
import { PageCommentProps } from '@chirpy-dev/ui';
import {
GetStaticPaths,
GetStaticProps,
GetStaticPropsContext,
GetStaticPropsResult,
InferGetStaticPropsType,
} from 'next';
import { log } from 'next-axiom';
import superjson from 'superjson';

export type PageCommentProps = InferGetStaticPropsType<typeof getStaticProps>;

/**
* Comment tree widget for a page
* @param props
Expand Down Expand Up @@ -48,10 +46,7 @@ export const getStaticPaths: GetStaticPaths<PathParams> = async () => {
return { paths, fallback: 'blocking' };
};

type StaticProps = PathParams &
CommonWidgetProps & {
pageId: string;
};
type StaticProps = PageCommentProps;
type StaticError = {
error: string;
};
Expand All @@ -72,6 +67,22 @@ export const getStaticProps: GetStaticProps<
where: {
url: pageURL,
},
select: {
id: true,
url: true,
authorId: true,
project: {
select: {
id: true,
theme: true,
user: {
select: {
plan: true,
},
},
},
},
},
});
const pageId = page?.id;
if (!pageId) {
Expand All @@ -83,37 +94,18 @@ export const getStaticProps: GetStaticProps<
url: pageURL,
});

const pageByPk = await prisma.page.findUnique({
where: {
id: pageId,
},
select: {
project: {
select: {
id: true,
theme: true,
user: {
select: {
plan: true,
},
},
},
},
},
});
if (!pageByPk?.project.id) {
log.error(`Can't find theme info`);
if (!page.project.id) {
log.error(`Can't find the project`, page);
return { notFound: true };
}
return {
props: {
trpcState: ssg.dehydrate(),
pageURL,
pageId,
projectId: pageByPk.project.id,
theme: (pageByPk.project.theme as Theme) || null,
page,
projectId: page.project.id,
theme: (page.project.theme as Theme) || null,
isWidget: true,
plan: pageByPk.project.user?.plan || 'HOBBY',
plan: page.project.user?.plan || 'HOBBY',
},
revalidate: 5 * 60,
};
Expand Down
6 changes: 3 additions & 3 deletions apps/main/src/pages/widget/comment/timeline/[commentId].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ export const getStaticProps: GetStaticProps<
select: {
id: true,
url: true,
authorId: true,
project: {
select: {
id: true,
Expand All @@ -76,17 +77,16 @@ export const getStaticProps: GetStaticProps<
},
});
if (!data?.page.project.id) {
log.error(`Can't find theme info`);
log.error(`Can't find the project`, data || undefined);
return { notFound: true };
}

return {
props: {
trpcState: ssg.dehydrate(),
pageId: data.page.id,
page: data.page,
projectId: data.page.project.id,
commentId,
pageURL: data.page.url,
theme: (data.page.project.theme as Theme) || null,
isWidget: true,
plan: data.page.project.user?.plan || 'HOBBY',
Expand Down
7 changes: 7 additions & 0 deletions apps/main/vercel.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"functions": {
"src/pages/**/*": {
"maxDuration": 50
}
}
}
1 change: 1 addition & 0 deletions packages/sdk/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.env*
3 changes: 2 additions & 1 deletion packages/sdk/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@chirpy-dev/sdk",
"version": "0.0.2",
"version": "0.0.5",
"license": "AGPL-3.0-or-later",
"main": "./lib/index.js",
"types": "./lib/index.d.ts",
Expand All @@ -9,6 +9,7 @@
},
"sideEffects": false,
"devDependencies": {
"@chirpy-dev/tsconfigs": "workspace:*",
"dotenv": "16.3.1",
"typescript": "5.2.2"
},
Expand Down
7 changes: 5 additions & 2 deletions packages/sdk/src/sdk.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,11 @@ async function test() {
process.env.CHIRPY_SDK_KEY!,
'http://localhost:3000',
);
const proj = await sdk.getProject('chirpy.dev');
console.log(proj);
const page = await sdk.getPage('http://localhost:3000/play');
console.log(page);
const user = await sdk.createUser('pickle@mac.com', 'Pickle');
console.log(user);
await sdk.linkPageAuthor('http://localhost:3000/play', user.id);
}

test();
Loading

0 comments on commit 92a1952

Please sign in to comment.