Skip to content

Commit

Permalink
improve env replit db & auth api and docs
Browse files Browse the repository at this point in the history
  • Loading branch information
slmjkdbtl committed Sep 23, 2021
1 parent c59dea8 commit 3cf95df
Show file tree
Hide file tree
Showing 7 changed files with 168 additions and 40 deletions.
84 changes: 59 additions & 25 deletions env/helper.js → env/helper.ts
Expand Up @@ -37,37 +37,45 @@ devws.onmessage = (e) => {
}
};

// replit auth
window.replit = {

user: null,

getUser() {
interface User {
id: string,
name: string,
}

interface Replit {
getUser(): Promise<User | null>,
auth(): Promise<User | null>,
getUserOrAuth(): Promise<User | null>,
getData<D = any>(key: string, def?: D): Promise<D>,
setData<D>(key: string, val: D): Promise<D>,
delData(key: string): Promise<void>,
listData(): Promise<string[]>,
clearData(): Promise<void>,
}

declare global {
const replit: Replit;
}

// replit auth & db integration
const replit: Replit = {

getUser(): Promise<User | null> {
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<User | null> {

return new Promise((resolve, reject) => {

if (this.authed()) {
resolve(this.user);
return;
}

const authComplete = (e) => {
if (e.data !== "auth_complete") {
resolve(null);
Expand Down Expand Up @@ -95,12 +103,21 @@ window.replit = {

},

};

// replit db
window.db = {
getUserOrAuth(): Promise<User | null> {
return new Promise((resolve, reject) => {
this.getUser().then((user) => {
if (user) {
resolve(user);
} else {
this.auth().then((user) => {
resolve(user);
})
}
})
});
},

getData(key, def) {
getData<D = any>(key: string, def?: D): Promise<D> {
return fetch(`/db/${key}`)
.then((res) => res.json())
.then((val) => {
Expand All @@ -112,7 +129,7 @@ window.db = {
});
},

setData(key, val) {
setData<D>(key: string, val: D): Promise<D> {
return fetch(`/db/${key}`, {
method: "POST",
headers: {
Expand All @@ -122,6 +139,23 @@ window.db = {
}).then(() => Promise.resolve(val));
},

delData(key: string): Promise<void> {
return fetch(`/db/${key}`, {
method: "DELETE",
}).then(() => {});
},

listData(): Promise<string[]> {
return fetch(`/db`)
.then((res) => res.json());
},

clearData(): Promise<void> {
return fetch(`/db`, {
method: "DELETE",
}).then((res) => {});
},

};

replit.getUser();
window.replit = replit;
82 changes: 82 additions & 0 deletions 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<Data | null>`

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<Data>`

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<void>`

Delete a key from database.

### `replit.listData(): Promise<string[]>`

Get all keys in database.

### `replit.clearData(): Promise<void>`

**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<User | null>`

Opens a window that prompts user to log in and authenticate. Returns a Promise that contains the user data if successful.

### `replit.getUser(): Promise<User | null>`

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<User | null>`

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.
11 changes: 6 additions & 5 deletions env/learn/flappy.md
@@ -1,4 +1,4 @@
### Build a Flappy Bird in Kaboom
# Build a Flappy Bird in Kaboom

(tutorial coming soon)

Expand Down Expand Up @@ -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')
Expand Down Expand Up @@ -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",
]);
Expand All @@ -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, },
Expand Down Expand Up @@ -154,3 +154,4 @@ scene("lose", (score) => {

go("game");
```

3 changes: 0 additions & 3 deletions env/learn/platformer.md

This file was deleted.

3 changes: 0 additions & 3 deletions env/learn/shooter.md

This file was deleted.

23 changes: 20 additions & 3 deletions env/run.js
Expand Up @@ -41,7 +41,7 @@ function buildGame() {
sourcemap: true,
target: "es6",
keepNames: true,
entryPoints: ["helper.js"],
entryPoints: ["helper.ts"],
outfile: "dist/helper.js",
});

Expand Down Expand Up @@ -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());
Expand All @@ -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));
Expand All @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion 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",
Expand Down

0 comments on commit 3cf95df

Please sign in to comment.