From 3cf95df3e32b0e554b9df63dc9a59e54843c5aac Mon Sep 17 00:00:00 2001 From: tga Date: Thu, 23 Sep 2021 19:24:23 -0400 Subject: [PATCH] improve env replit db & auth api and docs --- env/{helper.js => helper.ts} | 84 +++++++++++++++++++++++++----------- env/learn/DB & Auth.md | 82 +++++++++++++++++++++++++++++++++++ env/learn/flappy.md | 11 ++--- env/learn/platformer.md | 3 -- env/learn/shooter.md | 3 -- env/run.js | 23 ++++++++-- package.json | 2 +- 7 files changed, 168 insertions(+), 40 deletions(-) rename env/{helper.js => helper.ts} (64%) create mode 100644 env/learn/DB & Auth.md delete mode 100644 env/learn/platformer.md delete mode 100644 env/learn/shooter.md diff --git a/env/helper.js b/env/helper.ts similarity index 64% rename from env/helper.js rename to env/helper.ts index 0d32f9a43..c3cb54522 100644 --- a/env/helper.js +++ b/env/helper.ts @@ -37,37 +37,45 @@ devws.onmessage = (e) => { } }; -// replit auth -window.replit = { - - user: null, - - getUser() { +interface User { + id: string, + name: string, +} + +interface Replit { + getUser(): Promise, + auth(): Promise, + getUserOrAuth(): Promise, + getData(key: string, def?: D): Promise, + setData(key: string, val: D): Promise, + delData(key: string): Promise, + listData(): Promise, + clearData(): Promise, +} + +declare global { + const replit: Replit; +} + +// replit auth & db integration +const replit: Replit = { + + getUser(): Promise { return fetch("/user") .then((res) => res.json()) .then((user) => { if (user) { - this.user = user; - return Promise.resolve(this.user); + return Promise.resolve(user); } else { return Promise.resolve(null); } }); }, - authed() { - return this.user !== null; - }, - - auth() { + auth(): Promise { return new Promise((resolve, reject) => { - if (this.authed()) { - resolve(this.user); - return; - } - const authComplete = (e) => { if (e.data !== "auth_complete") { resolve(null); @@ -95,12 +103,21 @@ window.replit = { }, -}; - -// replit db -window.db = { + getUserOrAuth(): Promise { + return new Promise((resolve, reject) => { + this.getUser().then((user) => { + if (user) { + resolve(user); + } else { + this.auth().then((user) => { + resolve(user); + }) + } + }) + }); + }, - getData(key, def) { + getData(key: string, def?: D): Promise { return fetch(`/db/${key}`) .then((res) => res.json()) .then((val) => { @@ -112,7 +129,7 @@ window.db = { }); }, - setData(key, val) { + setData(key: string, val: D): Promise { return fetch(`/db/${key}`, { method: "POST", headers: { @@ -122,6 +139,23 @@ window.db = { }).then(() => Promise.resolve(val)); }, + delData(key: string): Promise { + return fetch(`/db/${key}`, { + method: "DELETE", + }).then(() => {}); + }, + + listData(): Promise { + return fetch(`/db`) + .then((res) => res.json()); + }, + + clearData(): Promise { + return fetch(`/db`, { + method: "DELETE", + }).then((res) => {}); + }, + }; -replit.getUser(); +window.replit = replit; diff --git a/env/learn/DB & Auth.md b/env/learn/DB & Auth.md new file mode 100644 index 000000000..d2771529b --- /dev/null +++ b/env/learn/DB & Auth.md @@ -0,0 +1,82 @@ +# Replit DB & Auth Integration + +A global `replit` object is exposed, containing all functions you need for interacting with Replit Auth and DB. + +## Database + +### `replit.getData(key: string, default?: Data): Promise` + +Get data from replit db, returns a `Promise` containing the data (`null` if key doesn't exists). Data is automatically `JSON.parsed()`-ed. Can optionally provide `default` to set the default value if the key doesn't exist. + +### `replit.setData(key: string, val: Data): Promise` + +Set data to replit db. Data is automatically `JSON.stringify()`-ed. Returns a `Promise` that resolves when the operation is complete. + +### `replit.delData(key: string): Promise` + +Delete a key from database. + +### `replit.listData(): Promise` + +Get all keys in database. + +### `replit.clearData(): Promise` + +**BE CAREFUL** Nuke the database. + +Database Example: + +```js +// get current high score from DB +db.getData("highscore").then((highscore) => { + + // update highest score in DB if user just got a higer one + if (score > highscore) { + highscore = score; + db.setData("highscore", highscore); + } + + add([ + text("High score: " + highscore), + pos(20, 20), + ]); + +}); +``` + + +## Auth + +### `replit.auth(): Promise` + +Opens a window that prompts user to log in and authenticate. Returns a Promise that contains the user data if successful. + +### `replit.getUser(): Promise` + +Get the user without initiating an auth process. Returns a Promise of the user if they're already authed (has auth token in cookies), `null` if not. + +### `replit.getUserOrAuth(): Promise` + +Like `getUser()`, but initiates an auth if auth doesn't exist. + +a `User` looks like this: + +```ts +User { + id: string, + name: string, +} +``` + +Auth Example: + +```js +replit.getUserOrAuth().then((user) => { + if (user) { + // insert an entry to DB with the user name as key + replit.setData(user.name, 0); + } +}); +``` + +Check out `helper.ts` and `run.js` to see how they work and tweak around. diff --git a/env/learn/flappy.md b/env/learn/flappy.md index 1e5c57975..79b573257 100644 --- a/env/learn/flappy.md +++ b/env/learn/flappy.md @@ -1,4 +1,4 @@ -### Build a Flappy Bird in Kaboom +# Build a Flappy Bird in Kaboom (tutorial coming soon) @@ -27,9 +27,6 @@ scene("game", () => { "ui", ], "obj"); - // background - addSky(); - // a game object consists of a list of components and tags const bean = add([ // sprite() means it's drawn with a sprite of name "bean" (defined above in 'loadSprite') @@ -72,7 +69,10 @@ scene("game", () => { color(0, 127, 255), outline(4), area(), + // move it towards the left SPEED pixels per second move(LEFT, SPEED), + // auto removal when it's out of screen, for maintaining performance + cleanup(), // give it tags to easier define behaviors see below "pipe", ]); @@ -84,7 +84,7 @@ scene("game", () => { outline(4), area(), move(LEFT, SPEED), - // give it tags to easier define behaviors see below + cleanup(), "pipe", // raw obj just assigns every field to the game obj { passed: false, }, @@ -154,3 +154,4 @@ scene("lose", (score) => { go("game"); ``` + diff --git a/env/learn/platformer.md b/env/learn/platformer.md deleted file mode 100644 index 00b262029..000000000 --- a/env/learn/platformer.md +++ /dev/null @@ -1,3 +0,0 @@ -### Build a Shooter Game in Kaboom - -coming soon diff --git a/env/learn/shooter.md b/env/learn/shooter.md deleted file mode 100644 index 00b262029..000000000 --- a/env/learn/shooter.md +++ /dev/null @@ -1,3 +0,0 @@ -### Build a Shooter Game in Kaboom - -coming soon diff --git a/env/run.js b/env/run.js index 53304db90..c2dbd0e54 100644 --- a/env/run.js +++ b/env/run.js @@ -41,7 +41,7 @@ function buildGame() { sourcemap: true, target: "es6", keepNames: true, - entryPoints: ["helper.js"], + entryPoints: ["helper.ts"], outfile: "dist/helper.js", }); @@ -100,7 +100,6 @@ app.get("/user", (req, res) => { } }); -// TODO: authed user level abstraction? app.get("/db", async (req, res) => { try { res.json(await db.list()); @@ -109,6 +108,15 @@ app.get("/db", async (req, res) => { } }); +app.delete("/db", async (req, res) => { + try { + await db.empty(); + res.sendStatus(200); + } catch (e) { + res.sendStatus(500); + } +}); + app.get("/db/:item", async (req, res) => { try { res.json(await db.get(req.params.item)); @@ -119,7 +127,16 @@ app.get("/db/:item", async (req, res) => { app.post("/db/:item", async (req, res) => { try { - db.set(req.params.item, req.body); + await db.set(req.params.item, req.body); + res.sendStatus(200); + } catch (e) { + res.sendStatus(500); + } +}); + +app.delete("/db/:item", async (req, res) => { + try { + await db.delete(req.params.item); res.sendStatus(200); } catch (e) { res.sendStatus(500); diff --git a/package.json b/package.json index b072572c0..3e958c841 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "kaboom", "description": "kaboom.js is a JavaScript library that helps you make games fast and fun!", - "version": "2000.0.0-beta.21", + "version": "2000.0.0-beta.22", "license": "MIT", "homepage": "https://kaboomjs.com/", "repository": "github:replit/kaboom",