Skip to content

Commit

Permalink
fresh sessions upgrade
Browse files Browse the repository at this point in the history
and more
  • Loading branch information
digitaldesigndj committed Jul 28, 2023
1 parent 4fdd680 commit 5e9ec00
Show file tree
Hide file tree
Showing 12 changed files with 499 additions and 116 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/deno.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ jobs:
# uses: denoland/setup-deno@v1
uses: denoland/setup-deno@v1
with:
deno-version: v1.30.3
deno-version: v1.35.3

- name: Verify formatting
run: deno fmt --check
Expand Down
25 changes: 20 additions & 5 deletions deno.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
{
"tasks": {
"start": "deno run -A --watch=static/,routes/ --lock=deno.lock dev.ts",
"run": "DENO_DEPLOYMENT_ID=$(git rev-parse --short HEAD) deno run -A --lock=deno.lock main.ts",
"reload": "deno run -A --watch=static/,routes/ --lock=deno.lock --reload dev.ts"
"start": "deno run -A --unstable --watch=static/,routes/ --lock=deno.lock dev.ts",
"run": "DENO_DEPLOYMENT_ID=$(git rev-parse --short HEAD) deno run -A --unstable --lock=deno.lock main.ts",
"reload": "deno run -A --unstable --watch=static/,routes/ --lock=deno.lock --reload dev.ts"
},
"importMap": "./import_map.json",
"compilerOptions": {
"jsx": "react-jsx",
"jsxImportSource": "preact"
Expand All @@ -14,5 +13,21 @@
"semiColons": false
}
},
"lock": false
"lock": false,
"imports": {
"@/": "./",
"$fresh/": "https://deno.land/x/fresh@1.3.1/",
"$std/": "https://deno.land/std@0.196.0/",
"fresh_seo": "https://deno.land/x/fresh_seo@0.2.1/mod.ts",
"preact": "https://esm.sh/preact@10.15.1",
"preact/": "https://esm.sh/preact@10.15.1/",
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.1.0",
"twind": "https://esm.sh/twind@0.16.19",
"twind/": "https://esm.sh/twind@0.16.19/",
"redis": "https://deno.land/x/redis@v0.29.0/mod.ts",
"@preact/signals": "https://esm.sh/*@preact/signals@1.1.3",
"@preact/signals-core": "https://esm.sh/*@preact/signals-core@1.2.3",
"envalid": "https://deno.land/x/envalid@0.1.2/mod.ts",
"fresh-session/": "https://deno.land/x/fresh_session@0.2.2/"
}
}
341 changes: 341 additions & 0 deletions deno.lock

Large diffs are not rendered by default.

2 changes: 0 additions & 2 deletions fresh.gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
// This file SHOULD be checked into source version control.
// This file is automatically updated during development when running `dev.ts`.

import config from "./deno.json" assert { type: "json" }
import * as $0 from "./routes/_404.jsx"
import * as $1 from "./routes/_middleware.jsx"
import * as $2 from "./routes/deal.jsx"
Expand Down Expand Up @@ -32,7 +31,6 @@ const manifest = {
"./islands/PokerPlayer.jsx": $$3,
},
baseUrl: import.meta.url,
config,
}

export default manifest
18 changes: 0 additions & 18 deletions import_map.json

This file was deleted.

147 changes: 77 additions & 70 deletions routes/_middleware.jsx
Original file line number Diff line number Diff line change
@@ -1,73 +1,79 @@
// routes/_middleware.js
import { blue, cyan, green, magenta, red, yellow } from "$std/fmt/colors.ts"
import { getCookies, setCookie } from "$std/http/cookie.ts"
import * as redis from "redis"
import { kvSession } from "fresh-session/mod.ts"

// import { getCookies, setCookie } from "$std/http/cookie.ts"
// import * as redis from "redis"
import {
// API_URL,
BASE_URL,
DENO_ENV,
REDIS_HOST,
REDIS_PASS,
REDIS_PORT,
// REDIS_HOST,
// REDIS_PASS,
// REDIS_PORT,
} from "@/utils/config.js"

const store = await redis.connect({
password: REDIS_PASS,
hostname: REDIS_HOST,
port: REDIS_PORT,
})
// const store = await redis.connect({
// password: REDIS_PASS,
// hostname: REDIS_HOST,
// port: REDIS_PORT,
// })

const COOKIE_NAME = "sesh"
const REDIS_KEY = (COOKIE_VALUE) => `devvideopoker-${COOKIE_VALUE}`
// const COOKIE_NAME = "sesh"
// const REDIS_KEY = (COOKIE_VALUE) => `devvideopoker-${COOKIE_VALUE}`

// Session Tracker
const createSession = async () => {
const session = {
// cart: [],
}
session[COOKIE_NAME] = crypto.randomUUID()
await store.set(REDIS_KEY(session[COOKIE_NAME]), JSON.stringify(session))
await store.expire(REDIS_KEY(session[COOKIE_NAME]), 7 * 24 * 60 * 60)
return session
}
// // Session Tracker
// const createSession = async () => {
// const session = {
// // cart: [],
// }
// session[COOKIE_NAME] = crypto.randomUUID()
// await store.set(REDIS_KEY(session[COOKIE_NAME]), JSON.stringify(session))
// await store.expire(REDIS_KEY(session[COOKIE_NAME]), 7 * 24 * 60 * 60)
// return session
// }

const setupNewSession = async (req, ctx) => {
ctx.state = await createSession()
ctx.REDIS_KEY = REDIS_KEY(ctx.state[COOKIE_NAME])
setupState(req, ctx)
const resp = await ctx.next()
setCookie(resp.headers, {
name: COOKIE_NAME,
value: ctx.state[COOKIE_NAME],
path: "/",
})
return resp
}
// const setupNewSession = async (req, ctx) => {
// ctx.state = await createSession()
// ctx.REDIS_KEY = REDIS_KEY(ctx.state[COOKIE_NAME])
// setupState(req, ctx)
// const resp = await ctx.next()
// setCookie(resp.headers, {
// name: COOKIE_NAME,
// value: ctx.state[COOKIE_NAME],
// path: "/",
// })
// return resp
// }

const setupSession = async (req, ctx) => {
const cookies = getCookies(req.headers)
if (cookies[COOKIE_NAME]) {
const session = await store.get(REDIS_KEY(cookies[COOKIE_NAME]))
if (session) {
ctx.state = JSON.parse(session)
ctx.REDIS_KEY = REDIS_KEY(cookies[COOKIE_NAME])
} else {
return await setupNewSession(req, ctx)
}
} else {
return await setupNewSession(req, ctx)
}
setupState(req, ctx)
return await ctx.next()
}
// const setupSession = async (req, ctx) => {
// const cookies = getCookies(req.headers)
// if (cookies[COOKIE_NAME]) {
// const session = await store.get(REDIS_KEY(cookies[COOKIE_NAME]))
// if (session) {
// ctx.state = JSON.parse(session)
// ctx.REDIS_KEY = REDIS_KEY(cookies[COOKIE_NAME])
// } else {
// return await setupNewSession(req, ctx)
// }
// } else {
// return await setupNewSession(req, ctx)
// }
// setupState(req, ctx)
// return await ctx.next()
// }

const setupState = (req, ctx) => {
// req.url.replace("http:", "https:");
const url = new URL(req.url)
ctx.state.url = url
}
// const setupState = (req, ctx) => {
// // req.url.replace("http:", "https:");
// const url = new URL(req.url)
// ctx.state.url = url
// }

export async function handler(req, ctx) {
const session = kvSession(null, {
maxAge: 10,
httpOnly: true,
})
// For Logging
const start = Date.now()
const { pathname } = new URL(req.url)
Expand All @@ -86,29 +92,30 @@ export async function handler(req, ctx) {
// ctx.API_URL = API_URL;
ctx.BASE_URL = BASE_URL
ctx.DENO_ENV = DENO_ENV
ctx.store = store
resp = await setupSession(req, ctx)
// ctx.store = store
resp = session(req, ctx)
} else {
resp = await ctx.next()
}
const now = Date.now()
const ms = now - start
const status = () => {
const str = resp.status.toString()
if (str[0] === "2") {
return green(str)
}
if (str[0] === "3") {
return yellow(str)
} else {
return red(str)
}
}
resp.headers.set("X-Response-Time", `${ms}ms`)
// const status = () => {
// const str = resp.status.toString()
// console.log(str)
// if (str[0] === "2") {
// return green(str)
// }
// if (str[0] === "3") {
// return yellow(str)
// } else {
// return red(str)
// }
// }
// resp.headers.set("X-Response-Time", `${ms}ms`)
console.log(
`[${magenta(new Date(now).toISOString())}] ${blue(req.method)} ${
cyan(pathname)
} - ${blue(String(ms) + "ms")} - ${status()}`,
} - ${blue(String(ms) + "ms")} - ${resp.status}`,
)
return resp
}
5 changes: 3 additions & 2 deletions routes/deal.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ import Keyboard from "@/islands/Keyboard.jsx"

export const handler = {
GET: (req, ctx) => {
const { session } = ctx.state
const deck = getNewCards()
const deck_id = crypto.randomUUID()
const cards = [...deck].splice(0, 5)
ctx.store.set(`deck-${deck_id}`, JSON.stringify({ deck }))
ctx.store.expire(`deck-${deck_id}`, 5 * 60)
session.set(`deck-${deck_id}`, JSON.stringify({ deck }))
// ctx.store.expire(`deck-${deck_id}`, 5 * 60)
return ctx.render({ ...ctx.state, cards, deck_id })
},
POST: async (req, ctx) => {
Expand Down
23 changes: 16 additions & 7 deletions routes/draw.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@ export const handler = {
return ctx.renderNotFound()
},
POST: async (req, ctx) => {
const { session } = ctx.state
const data = await req.formData()
console.log(data)
// const deck = getNewCards();
// const deck_id = crypto.randomUUID();
// const cards = deck.splice(0, 5);
const deck_id = data.get("deck_id")
const redis_data = await ctx.store.get(`deck-${deck_id}`)
const redis_data = session.get(`deck-${deck_id}`)
// await ctx.store.get(`deck-${deck_id}`)
if (redis_data) {
const hold_1 = data.get("hold_1") ? true : false
const hold_2 = data.get("hold_2") ? true : false
Expand All @@ -30,7 +32,7 @@ export const handler = {
const next = [...redis_data_parsed.deck].splice(5, 5)
const cards = holds.map((v, i) => v ? hand[i] : next[i])
const strategy = simpleStrategy(hand)
console.log(user_strategy, strategy.strategy)
// console.log(user_strategy, strategy.strategy)
const winner =
JSON.stringify(user_strategy) === JSON.stringify(strategy.strategy)
? true
Expand All @@ -43,17 +45,24 @@ export const handler = {
})
// console.log(redis_data_parsed.deck.length, "deck length");
if (winner) {
if (ctx.state.streak) {
ctx.state.streak = ctx.state.streak + 1
console.log(session.data, "datas")
if (session.has("streak")) {
const streak = session.get("streak") + 1
ctx.state.streak = streak
session.set("streak", streak)
} else {
session.set("streak", 1)
ctx.state.streak = 1
}
} else {
ctx.state.final = parseInt(ctx.state.streak)
ctx.state.final = session.get("streak")
session.set("streak", 0)
ctx.state.streak = 0
}
ctx.store.set(ctx.REDIS_KEY, JSON.stringify({ ...ctx.state }))
ctx.store.expire(`deck-${deck_id}`, 0)
// ctx.store.set(ctx.REDIS_KEY, JSON.stringify({ ...ctx.state }))
session.set(ctx.REDIS_KEY, JSON.stringify({ ...ctx.state }))
// ctx.store.expire(`deck-${deck_id}`, 0)
session.set(`deck-${deck_id}`, null)
return ctx.render({
...ctx.state,
cards,
Expand Down
18 changes: 10 additions & 8 deletions test/1_puppet_test.js
Original file line number Diff line number Diff line change
@@ -1,51 +1,53 @@
import { assertEquals } from "$std/testing/asserts.ts"
import { freshPuppetTestWrapper } from "fresh_marionette"
import { assert, assertEquals } from "$std/assert/mod.ts"
import { freshPuppetTestWrapper } from "@/test/wrapper.js"
import { BASE_URL } from "@/utils/config.js"
import { puppet_config } from "@/test/config.js"
import { Status } from "$std/http/http_status.ts"

Deno.test(
"Public Pages Testing",
{ sanitizeResources: false, sanitizeOps: false },
freshPuppetTestWrapper(puppet_config, async (t, page) => {
await t.step("The homepage should work", async () => {
const response = await page.goto(`${BASE_URL}`, {
waitUntil: "networkidle2",
})
assertEquals(response.status(), 200)
assert(response.ok)
})

await t.step("The sitemap should work", async () => {
const response = await page.goto(`${BASE_URL}/sitemap.xml`, {
waitUntil: "networkidle2",
})
assertEquals(response.status(), 200)
assert(response.ok)
})

await t.step("The deal page should work", async () => {
const response = await page.goto(`${BASE_URL}/deal`, {
waitUntil: "networkidle2",
})
assertEquals(response.status(), 200)
assert(response.ok)
})

await t.step("The draw page should 404 a GET", async () => {
const response = await page.goto(`${BASE_URL}/draw`, {
waitUntil: "networkidle2",
})
assertEquals(response.status(), 404)
assertEquals(response.status(), Status.NotFound)
})

await t.step("The player page should work", async () => {
const response = await page.goto(`${BASE_URL}/player`, {
waitUntil: "domcontentloaded",
})
assertEquals(response.status(), 200)
assert(response.ok)
})

await t.step("The deal page should allow gameplay", async () => {
const response = await page.goto(`${BASE_URL}/deal`, {
waitUntil: "networkidle2",
})
assertEquals(response.status(), 200)
assertEquals(response.status(), Status.OK)
await page.click('[type="submit"]')
await page.waitForNetworkIdle()
assertEquals(page.url(), `${BASE_URL}/draw`)
Expand Down
Loading

0 comments on commit 5e9ec00

Please sign in to comment.