Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add perf logs #1

Open
wants to merge 16 commits into
base: ab-test
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"editor.defaultFormatter": "Prisma.prisma"
},
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
"source.fixAll.eslint": "explicit"
},
"files.associations": {
"*.css": "postcss"
Expand Down
4 changes: 2 additions & 2 deletions apps/admin/cypress/support/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ function setContent({ title, content }: { title?: string; content?: string }) {
win.document.body.click();
//@ts-ignore
win.tinymce.get("title-editor").setContent(title);
cy.wait("@UpdatePostMutation");
// cy.wait("@UpdatePostMutation");
});
}
if (content) {
Expand All @@ -66,7 +66,7 @@ function setContent({ title, content }: { title?: string; content?: string }) {
win.document.body.click();
//@ts-ignore
win.tinymce.get("main-editor").setContent(content);
cy.wait("@UpdatePostMutation");
// cy.wait("@UpdatePostMutation");
});
}
}
Expand Down
2 changes: 1 addition & 1 deletion apps/admin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@
"streamifier": "^0.1.1",
"stripe": "^10.15.0",
"swr": "1.3.0",
"tinymce": "^6.7.0",
"tinymce": "6.7.2",
"twig": "^1.15.4",
"ui": "*",
"urql": "^4.0.5"
Expand Down
153 changes: 153 additions & 0 deletions apps/admin/src/app/api/_cors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
/**
* Multi purpose CORS lib.
* Note: Based on the `cors` package in npm but using only
* web APIs. Feel free to use it in your own projects.
*/

type StaticOrigin = boolean | string | RegExp | (boolean | string | RegExp)[];

type OriginFn = (
origin: string | undefined,
req: Request
) => StaticOrigin | Promise<StaticOrigin>;

interface CorsOptions {
origin?: StaticOrigin | OriginFn;
methods?: string | string[];
allowedHeaders?: string | string[];
exposedHeaders?: string | string[];
credentials?: boolean;
maxAge?: number;
preflightContinue?: boolean;
optionsSuccessStatus?: number;
}

const defaultOptions: CorsOptions = {
origin: "*",
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
preflightContinue: false,
optionsSuccessStatus: 204,
};

function isOriginAllowed(origin: string, allowed: StaticOrigin): boolean {
return Array.isArray(allowed)
? allowed.some((o) => isOriginAllowed(origin, o))
: typeof allowed === "string"
? origin === allowed
: allowed instanceof RegExp
? allowed.test(origin)
: !!allowed;
}

function getOriginHeaders(reqOrigin: string | undefined, origin: StaticOrigin) {
const headers = new Headers();

if (origin === "*") {
// Allow any origin
headers.set("Access-Control-Allow-Origin", "*");
} else if (typeof origin === "string") {
// Fixed origin
headers.set("Access-Control-Allow-Origin", origin);
headers.append("Vary", "Origin");
} else {
const allowed = isOriginAllowed(reqOrigin ?? "", origin);

if (allowed && reqOrigin) {
headers.set("Access-Control-Allow-Origin", reqOrigin);
}
headers.append("Vary", "Origin");
}

return headers;
}

// originHeadersFromReq

async function originHeadersFromReq(
req: Request,
origin: StaticOrigin | OriginFn
) {
const reqOrigin = req.headers.get("Origin") || undefined;
const value =
typeof origin === "function" ? await origin(reqOrigin, req) : origin;

if (!value) return;
return getOriginHeaders(reqOrigin, value);
}

function getAllowedHeaders(req: Request, allowed?: string | string[]) {
const headers = new Headers();

if (!allowed) {
allowed = req.headers.get("Access-Control-Request-Headers")!;
headers.append("Vary", "Access-Control-Request-Headers");
} else if (Array.isArray(allowed)) {
// If the allowed headers is an array, turn it into a string
allowed = allowed.join(",");
}
if (allowed) {
headers.set("Access-Control-Allow-Headers", allowed);
}

return headers;
}

export default async function cors(
req: Request,
res: Response,
options?: CorsOptions
) {
const opts = { ...defaultOptions, ...options };
const { headers } = res;
const originHeaders = await originHeadersFromReq(req, opts.origin ?? false);
const mergeHeaders = (v: string, k: string) => {
if (k === "Vary") headers.append(k, v);
else headers.set(k, v);
};

// If there's no origin we won't touch the response
if (!originHeaders) return res;

originHeaders.forEach(mergeHeaders);

if (opts.credentials) {
headers.set("Access-Control-Allow-Credentials", "true");
}

const exposed = Array.isArray(opts.exposedHeaders)
? opts.exposedHeaders.join(",")
: opts.exposedHeaders;

if (exposed) {
headers.set("Access-Control-Expose-Headers", exposed);
}

// Handle the preflight request
if (req.method === "OPTIONS") {
if (opts.methods) {
const methods = Array.isArray(opts.methods)
? opts.methods.join(",")
: opts.methods;

headers.set("Access-Control-Allow-Methods", methods);
}

getAllowedHeaders(req, opts.allowedHeaders).forEach(mergeHeaders);

if (typeof opts.maxAge === "number") {
headers.set("Access-Control-Max-Age", String(opts.maxAge));
}

if (opts.preflightContinue) return res;

headers.set("Content-Length", "0");
return new Response(null, { status: opts.optionsSuccessStatus, headers });
}

// If we got here, it's a normal request
return res;
}

export function initCors(options?: CorsOptions) {
return (req: Request, res: Response) => cors(req, res, options);
}
13 changes: 13 additions & 0 deletions apps/admin/src/app/api/graphql/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import { maskIfUnauth } from "@/graphql/directives/maskIfUnauth";
import { resolversArr } from "@/graphql/resolvers";
import { typeDefsList } from "@/graphql/schema";

import cors from "../_cors";

export const setupYoga = (context) => {
return createYoga({
schema: maskIfUnauth("maskIfUnauth")(
Expand All @@ -25,6 +27,15 @@ export const setupYoga = (context) => {
const { handleRequest } = setupYoga(context);
export { handleRequest as GET, handleRequest as POST };

export async function OPTIONS(request: Request) {
return cors(
request,
new Response(null, {
status: 204,
})
);
}

type Awaited<T> = T extends null | undefined
? T // special case for `null | undefined` when not in `--strictNullChecks` mode
: T extends object & { then(onfulfilled: infer F): any } // `await` only unwraps object types with a callable `then`. Non-object types are not unwrapped
Expand All @@ -33,4 +44,6 @@ type Awaited<T> = T extends null | undefined
: never // the argument to `then` was not callable
: T; // non-object or non-thenable

// Added apollo server configuration

export type ResolverContext = Awaited<ReturnType<typeof context>>;
2 changes: 1 addition & 1 deletion apps/admin/src/app/api/sitemap.xml/route.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { NextResponse } from "next/server";

import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";
export async function GET() {
const lastModified = new Date().toISOString();

Expand Down
52 changes: 52 additions & 0 deletions apps/admin/src/app/home/loading.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,55 @@
import { PageSkeleton } from "@/components/skeleton";

export default PageSkeleton;

"use client"

import * as React from "react"
import * as AvatarPrimitive from "@radix-ui/react-avatar"

// import { cn } from "@/lib/utils"

// const Avatar = React.forwardRef<
// React.ElementRef<typeof AvatarPrimitive.Root>,
// React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Root>
// >(({ className, ...props }, ref) => (
// <AvatarPrimitive.Root
// ref={ref}
// className={cn(
// "relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",
// className
// )}
// {...props}
// />
// ))
// Avatar.displayName = AvatarPrimitive.Root.displayName

// const AvatarImage = React.forwardRef<
// React.ElementRef<typeof AvatarPrimitive.Image>,
// React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Image>
// >(({ className, ...props }, ref) => (
// <AvatarPrimitive.Image
// ref={ref}
// className={cn("aspect-square h-full w-full", className)}
// {...props}
// />
// ))
// AvatarImage.displayName = AvatarPrimitive.Image.displayName

// const AvatarFallback = React.forwardRef<
// React.ElementRef<typeof AvatarPrimitive.Fallback>,
// React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Fallback>
// >(({ className, ...props }, ref) => (
// <AvatarPrimitive.Fallback
// ref={ref}
// className={cn(
// "flex h-full w-full items-center justify-center rounded-full bg-muted",
// className
// )}
// {...props}
// />
// ))
// AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName

// export { Avatar, AvatarImage, AvatarFallback }

18 changes: 18 additions & 0 deletions apps/admin/src/app/home/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,21 @@ const Home: FC<PageProps> = ({ settings }) => {
);
};
export default Home;

// import { Search } from "lucide-react";
// import { Input } from "@/components/ui/input";

// export function SearchBar() {
// return (
// <div className="relative w-full max-w-sm">
// <div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
// <Search className="h-5 w-5 text-gray-400" />
// </div>
// <Input
// type="search"
// className="pl-10 pr-4 py-2 w-full h-12 rounded-lg border border-[#515670] focus:ring-2 focus:ring-blue-500 bg-transparent"
// placeholder="Search market"
// />
// </div>
// );
// }
1 change: 1 addition & 0 deletions apps/admin/src/app/settings/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Metadata } from "next";
import React from "react";
// import { getImageAttrs } from "@/graphql/utils/imageAttributs";

import { TwoColumnLayout } from "@/components/layouts/twoColumn";

Expand Down
36 changes: 36 additions & 0 deletions apps/admin/src/components/badge.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// import * as React from "react"
// import { cva, type VariantProps } from "class-variance-authority"

// import { cn } from "@/lib/utils"

// const badgeVariants = cva(
// "inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
// {
// variants: {
// variant: {
// default:
// "border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
// secondary:
// "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
// destructive:
// "border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
// outline: "text-foreground",
// },
// },
// defaultVariants: {
// variant: "default",
// },
// }
// )

// export interface BadgeProps
// extends React.HTMLAttributes<HTMLDivElement>,
// VariantProps<typeof badgeVariants> {}

// function Badge({ className, variant, ...props }: BadgeProps) {
// return (
// <div className={cn(badgeVariants({ variant }), className)} {...props} />
// )
// }

// export { Badge, badgeVariants }
33 changes: 24 additions & 9 deletions apps/admin/src/graphql/services/post/getPost.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
/* eslint-disable no-console */
import { Post } from "@prisma/client";

import { PostVersion } from "@/lib/versioning";

import {
Expand Down Expand Up @@ -74,16 +77,28 @@ export const getPost = async (
}

if (slug) {
const post = await prisma.post.findFirst({
where: {
author_id: client_author_id,
status: PostStatusOptions.Published,
slug: slug?.split("/").pop(),
},
});
// const post = await prisma.post.findFirst({
// where: {
// author_id: client_author_id,
// status: PostStatusOptions.Published,
// slug: slug?.split("/").pop(),
// },
// });

if (post) {
return { ...mapPostToGraphql(post), __typename: "Post" };
// Prisma has a problem with slow execution time. Writing this raw query because of that.
const cleanSlug = slug?.split("/").pop();

type t = ReturnType<typeof prisma.post.findFirst>;
console.time("Raw Way");
const post_ = await prisma.$queryRawUnsafe<[Post]>(
`SELECT p.id, p.title, p.sub_title, p.html, p.excerpt, p.cover_image, p.type, p.status, p.featured, p.slug, p.createdAt, p.publishedAt, p.scheduledAt, p.updatedAt, p.reading_time, p.page_type, p.page_data, p.author_id FROM Post p INNER JOIN Author a ON p.author_id = a.id WHERE p.slug = $1 AND p.status = $2 AND p.author_id = $3`,
`${cleanSlug}`,
"published",
client_author_id
);
console.timeEnd("Raw Way");
if (post_[0]) {
return { ...mapPostToGraphql(post_[0]), __typename: "Post" };
}
return {
__typename: "NotFound",
Expand Down
Loading
Loading