Skip to content

Commit

Permalink
Merge pull request #9 from solaoi/feature_add-ntimes-error-for-retry-…
Browse files Browse the repository at this point in the history
…checking

add ntimes error on request a endpoint for testing retry
  • Loading branch information
solaoi authored Oct 10, 2021
2 parents 2eeb3db + bd36203 commit 70f0ed1
Show file tree
Hide file tree
Showing 11 changed files with 224 additions and 43 deletions.
42 changes: 37 additions & 5 deletions app/api/[[...slug]].ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,25 @@ const Handler: BlitzApiHandler = async (req: BlitzApiRequest, res: BlitzApiRespo
if (!obj) {
return res.status(404).end()
}
const { id, contentType, statusCode, sleep, response, logs } = obj
if (sleep !== 0) {
await snooze(sleep * 1000)
}
const {
id,
contentType,
statusCode,
sleep,
response,
logs,
ntimesError,
ntimesErrorStatusCode,
ntimesErrorCounter,
} = obj

const ntimesErrorCount = (() => {
if (ntimesError === 0 || ntimesError === ntimesErrorCounter) {
return 0
} else {
return ntimesErrorCounter + 1
}
})()

const RECENT_LOGS = 3
const { slug: _, ...query } = req.query
Expand All @@ -55,8 +70,25 @@ const Handler: BlitzApiHandler = async (req: BlitzApiRequest, res: BlitzApiRespo
log,
...logArr.filter((_, i) => logArr.length < RECENT_LOGS || i !== logArr.length - 1),
].join("\t")
await db.stub.update({ where: { id }, data: { logs: updatedLogs } })

const inNtimesErrorTerm = ntimesError > 0 && ntimesError >= ntimesErrorCounter + 1
const sleepFunc = async () => {
if (!inNtimesErrorTerm && sleep !== 0) {
return snooze(sleep * 1000)
}
}

await Promise.all([
sleepFunc(),
db.stub.update({
where: { id },
data: { logs: updatedLogs, ntimesErrorCounter: ntimesErrorCount },
}),
])

if (inNtimesErrorTerm) {
return res.status(Number(ntimesErrorStatusCode)).end()
}
return res.status(Number(statusCode)).setHeader("Content-Type", contentType).end(response)
}

Expand Down
19 changes: 18 additions & 1 deletion app/core/components/LabeledTextField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,13 @@ import { forwardRef, PropsWithoutRef, ComponentPropsWithoutRef } from "react"
import { useField } from "react-final-form"

import { Input } from "@chakra-ui/input"
import {
NumberInput,
NumberInputField,
NumberInputStepper,
NumberIncrementStepper,
NumberDecrementStepper,
} from "@chakra-ui/react"
import { FormControl, FormLabel } from "@chakra-ui/form-control"

export interface LabeledTextFieldProps extends ComponentPropsWithoutRef<typeof Input> {
Expand Down Expand Up @@ -29,7 +36,17 @@ export const LabeledTextField = forwardRef<HTMLInputElement, LabeledTextFieldPro
<FormControl {...outerProps}>
<FormLabel>
{label}
<Input {...input} disabled={submitting} {...props} ref={ref} />
{props.type === "number" ? (
<NumberInput {...input} disabled={submitting} {...props} ref={ref}>
<NumberInputField />
<NumberInputStepper>
<NumberIncrementStepper />
<NumberDecrementStepper />
</NumberInputStepper>
</NumberInput>
) : (
<Input {...input} disabled={submitting} {...props} ref={ref} />
)}
</FormLabel>
{touched && normalizedError && (
<div role="alert" style={{ color: "red" }}>
Expand Down
12 changes: 10 additions & 2 deletions app/core/layouts/Card.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
import React from "react"
import { Box, Heading } from "@chakra-ui/react"

const Card = ({ heading, children }: { heading: string; children: any }) => {
const Card = ({
heading,
children,
bgColor = "#FFF",
}: {
heading: string
children: any
bgColor?: string
}) => {
return (
<Box maxW="sm" borderWidth="1px" borderRadius="lg" overflow="hidden">
<Box maxW="sm" borderWidth="1px" borderRadius="lg" overflow="hidden" bgColor={bgColor}>
<Box m="5">
<Heading mb="5" as="h4" size="md">
{heading}
Expand Down
84 changes: 66 additions & 18 deletions app/pages/stubs/[stubId].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -111,29 +111,77 @@ export const Stub = () => {
<Flex justify="space-between">
<Box flex="1">
<Flex direction="column" fontWeight="bold" color="#666">
<Text mb="1">path</Text>
<Text mb="1">createdBy</Text>
<Text mb="1">createdAt</Text>
<Text mb="1">updatedBy</Text>
<Text mb="1">updatedAt</Text>
<Text mb="1">method</Text>
<Text mb="1">contentType</Text>
<Text mb="1">statusCode</Text>
<Text mb="1">sleep</Text>
<Text mb="1" h="1.5rem">
path
</Text>
<Text mb="1" h="1.5rem">
createdBy
</Text>
<Text mb="1" h="1.5rem">
createdAt
</Text>
<Text mb="1" h="1.5rem">
updatedBy
</Text>
<Text mb="1" h="1.5rem">
updatedAt
</Text>
<Text mb="1" h="1.5rem">
method
</Text>
<Text mb="1" h="1.5rem">
contentType
</Text>
<Text mb="1" h="1.5rem">
statusCode
</Text>
<Text mb="1" h="1.5rem">
sleep
</Text>
<Text mb="1" h="1.5rem">
ntimesError
</Text>
<Text mb="1" h="1.5rem">
ntimesErrorStatusCode
</Text>
<Text>response</Text>
</Flex>
</Box>
<Box flex="2">
<Flex direction="column">
<Text mb="1">{stub.path}</Text>
<Text mb="1">{stub.createdBy}</Text>
<Text mb="1">{stub.createdAt.toLocaleString()}</Text>
<Text mb="1">{stub.updatedBy}</Text>
<Text mb="1">{stub.updatedAt.toLocaleString()}</Text>
<Text mb="1">{stub.method}</Text>
<Text mb="1">{stub.contentType}</Text>
<Text mb="1">{stub.statusCode}</Text>
<Text mb="1">{stub.sleep} s</Text>
<Text mb="1" h="1.5rem">
{stub.path}
</Text>
<Text mb="1" h="1.5rem">
{stub.createdBy}
</Text>
<Text mb="1" h="1.5rem">
{stub.createdAt.toLocaleString()}
</Text>
<Text mb="1" h="1.5rem">
{stub.updatedBy}
</Text>
<Text mb="1" h="1.5rem">
{stub.updatedAt.toLocaleString()}
</Text>
<Text mb="1" h="1.5rem">
{stub.method}
</Text>
<Text mb="1" h="1.5rem">
{stub.contentType}
</Text>
<Text mb="1" h="1.5rem">
{stub.statusCode}
</Text>
<Text mb="1" h="1.5rem">
{stub.sleep} s
</Text>
<Text mb="1" h="1.5rem">
{stub.ntimesError} times
</Text>
<Text mb="1" h="1.5rem">
{stub.ntimesErrorStatusCode}
</Text>
<Box w="100%" p="2" bgColor="#3c3c3c" color="#fff" borderRadius="lg">
<pre style={{ whiteSpace: "pre-wrap" }}>
{(() => {
Expand Down
5 changes: 4 additions & 1 deletion app/pages/stubs/[stubId]/edit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,10 @@ export const EditStub = () => {
<Flex align="center" justify="center" m="6">
<Card heading="Edit Stub">
<StubForm
initialValues={{ ...stub, updatedBy: currentUser?.name }}
initialValues={{
...stub,
updatedBy: currentUser?.name,
}}
submitText="UPDATE"
// TODO use a zod schema for form validation
// - Tip: extract mutation's schema into a shared `validations.ts` file and
Expand Down
8 changes: 7 additions & 1 deletion app/pages/stubs/new.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,13 @@ const NewStubPage: BlitzPage = () => {
<Flex align="center" justify="center" m="6">
<Card heading="New Stub">
<StubForm
initialValues={{ createdBy: currentUser?.name, updatedBy: currentUser?.name, sleep: 0 }}
initialValues={{
createdBy: currentUser?.name,
updatedBy: currentUser?.name,
sleep: 0,
ntimesError: 0,
ntimesErrorStatusCode: "500",
}}
submitText="ADD"
// TODO use a zod schema for form validation
// - Tip: extract mutation's schema into a shared `validations.ts` file and
Expand Down
25 changes: 24 additions & 1 deletion app/stubs/components/StubForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import { LabeledSelectField } from "app/core/components/LabeledSelectField"
import { useRouterQuery } from "blitz"
import { z } from "zod"
export { FORM_ERROR } from "app/core/components/Form"
import Card from "../../core/layouts/Card"
import { border } from "@chakra-ui/styled-system"

export function StubForm<S extends z.ZodType<any, any>>(props: FormProps<S>) {
const query = useRouterQuery()
Expand Down Expand Up @@ -43,8 +45,29 @@ export function StubForm<S extends z.ZodType<any, any>>(props: FormProps<S>) {
]}
/>
<LabeledTextField name="statusCode" label="StatusCode" placeholder="200" />
<LabeledTextField type="number" name="sleep" label="Sleep(seconds)" placeholder="0" />
<LabeledTextAreaField name="response" label="Response" placeholder="Response" />
<Card heading="Optional" bgColor="#E2E8F0">
<LabeledTextField
type="number"
name="sleep"
label="Sleep(seconds)"
placeholder="0"
style={{ borderColor: "#FFF" }}
/>
<LabeledTextField
type="number"
name="ntimesError"
label="NtimesError"
placeholder="0"
style={{ borderColor: "#FFF" }}
/>
<LabeledTextField
name="ntimesErrorStatusCode"
label="NtimesErrorStatusCode"
placeholder="500"
style={{ borderColor: "#FFF" }}
/>
</Card>
</Form>
)
}
5 changes: 5 additions & 0 deletions app/stubs/mutations/createStub.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ const CreateStub = z.object({
.regex(/^\d{3}$/, { message: "The status code must be a three-digit number." }),
response: z.string().default(""),
sleep: z.number().min(0).default(0),
ntimesError: z.number().min(0).default(0),
ntimesErrorStatusCode: z
.string()
.regex(/^\d{3}$/, { message: "The ntimes error status code must be a three-digit number." }),
ntimesErrorCounter: z.number().min(0).default(0),
logs: z.string().default(""),
projectId: z.number(),
})
Expand Down
4 changes: 4 additions & 0 deletions app/stubs/mutations/updateStub.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ const UpdateStub = z.object({
.regex(/^\d{3}$/, { message: "The status code must be a three-digit number." }),
response: z.string(),
sleep: z.number().min(0),
ntimesError: z.number().min(0).default(0),
ntimesErrorStatusCode: z
.string()
.regex(/^\d{3}$/, { message: "The ntimes error status code must be a three-digit number." }),
})

export default resolver.pipe(
Expand Down
32 changes: 32 additions & 0 deletions db/migrations/20211010133505_/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
Warnings:
- Added the required column `ntimesErrorStatusCode` to the `Stub` table without a default value. This is not possible if the table is not empty.
*/
-- RedefineTables
PRAGMA foreign_keys=OFF;
CREATE TABLE "new_Stub" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" DATETIME NOT NULL,
"createdBy" TEXT NOT NULL,
"updatedBy" TEXT NOT NULL,
"path" TEXT NOT NULL,
"method" TEXT NOT NULL,
"contentType" TEXT NOT NULL,
"statusCode" TEXT NOT NULL,
"response" TEXT NOT NULL,
"sleep" INTEGER NOT NULL DEFAULT 0,
"logs" TEXT NOT NULL,
"ntimesError" INTEGER NOT NULL DEFAULT 0,
"ntimesErrorStatusCode" TEXT NOT NULL,
"ntimesErrorCounter" INTEGER NOT NULL DEFAULT 0,
"projectId" INTEGER NOT NULL,
CONSTRAINT "Stub_projectId_fkey" FOREIGN KEY ("projectId") REFERENCES "Project" ("id") ON DELETE CASCADE ON UPDATE CASCADE
);
INSERT INTO "new_Stub" ("contentType", "createdAt", "createdBy", "id", "logs", "method", "path", "projectId", "response", "sleep", "statusCode", "updatedAt", "updatedBy") SELECT "contentType", "createdAt", "createdBy", "id", "logs", "method", "path", "projectId", "response", "sleep", "statusCode", "updatedAt", "updatedBy" FROM "Stub";
DROP TABLE "Stub";
ALTER TABLE "new_Stub" RENAME TO "Stub";
PRAGMA foreign_key_check;
PRAGMA foreign_keys=ON;
31 changes: 17 additions & 14 deletions db/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -76,18 +76,21 @@ model Project {
}

model Stub {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
createdBy String
updatedBy String
path String
method String
contentType String
statusCode String
response String
sleep Int
logs String
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
projectId Int
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
createdBy String
updatedBy String
path String
method String
contentType String
statusCode String
response String
sleep Int @default(0)
logs String
ntimesError Int @default(0)
ntimesErrorStatusCode String
ntimesErrorCounter Int @default(0)
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
projectId Int
}

0 comments on commit 70f0ed1

Please sign in to comment.