Skip to content

Commit

Permalink
(#4) Draw: draft
Browse files Browse the repository at this point in the history
  • Loading branch information
betarixm committed Mar 29, 2022
1 parent a4ba130 commit af8dcd3
Show file tree
Hide file tree
Showing 2 changed files with 86 additions and 0 deletions.
25 changes: 25 additions & 0 deletions pages/api/ponix/draw.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import type { NextApiRequest, NextApiResponse } from "next";
import type { Ponix } from "../../../typings/models";
import type { ApiError } from "../../../typings/errors";

import { EmptyPonix, PonixList } from "../../../constants/ponix";
import { DRAW_FAIL_RATE } from "../../../constants/variables";

export const internalHandler: () => Ponix = () => {
return Math.random() >= DRAW_FAIL_RATE
? PonixList[Math.floor(PonixList.length * Math.random())]
: EmptyPonix;
};

export const handler = (req: NextApiRequest, res: NextApiResponse<Ponix | ApiError>) => {
if (req.method === "POST") {
res.status(200).json(internalHandler());
} else {
res.status(405).json({
message: "Method Not Allowed",
redirect: "/draw",
});
}
};

export default handler;
61 changes: 61 additions & 0 deletions pages/draw.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import type { Ponix } from "../typings/models";

import React from "react";

import { GetServerSideProps } from "next";
import { internalHandler as apiDraw } from "./api/ponix/draw";

import { Layout } from "../layout";

import { LOCALSTORAGE_KEY } from "../constants/strings";
import PonixView from "../components/PonixView";

interface DrawProps {
ponix: Ponix;
}

interface DrawState {}

class Draw extends React.Component<DrawProps, DrawState> {
addPonixToStorage = (ponix: Ponix) => {
let items = JSON.parse(localStorage.getItem(LOCALSTORAGE_KEY) || "[]");
localStorage.setItem(
LOCALSTORAGE_KEY,
JSON.stringify([ponix.id, ...items.filter((i: string) => i != ponix.id)])
);
};

isDrawSuccess = (ponix: Ponix) => {
return ponix.no !== -1;
};

componentDidMount = () => {
if (this.isDrawSuccess(this.props.ponix)) {
this.addPonixToStorage(this.props.ponix);
}
};

render = () => {
const { ponix } = this.props;

const success = (
<>
<PonixView ponix={ponix} />
</>
);

const failed = <>Failed!</>;

return <Layout title={"Draw"}>{this.isDrawSuccess(ponix) ? success : failed}</Layout>;
};
}

export const getServerSideProps: GetServerSideProps<DrawProps> = async (context) => {
return {
props: {
ponix: apiDraw(),
},
};
};

export default Draw;

0 comments on commit af8dcd3

Please sign in to comment.