Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
The diff you're trying to view is too large. We only load the first 3000 changed files.
25 changes: 25 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
name: ci

on:
pull_request:
branches: [main]

jobs:
tests:
name: Tests
runs-on: ubuntu-latest

steps:
- name: Check out code
uses: actions/checkout@v4

- name: Set up Node
uses: actions/setup-node@v4
with:
node-version: 18

- name: Install dependencies
run: npm ci

- name: Run Test
run: npm run test
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,5 @@ npm run dev
_This starts the server in non-database mode._ It will serve a simple webpage at `http://localhost:8080`.

You do _not_ need to set up a database or any interactivity on the webpage yet. Instructions for that will come later in the course!

"AJ's version of boot.dev's notely app"
11 changes: 11 additions & 0 deletions dist/api/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export function getAPIKey(headers) {
const authHeader = headers["authorization"];
if (!authHeader) {
return null;
}
const splitAuth = authHeader.split(" ");
if (splitAuth.length < 2 || splitAuth[0] !== "ApiKey") {
return null;
}
return splitAuth[1];
}
27 changes: 27 additions & 0 deletions dist/api/json.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
export function respondWithError(res, code, message, logError) {
if (logError) {
console.log(errStringFromError(logError));
}
respondWithJSON(res, code, { error: message });
}
export function respondWithJSON(res, code, payload) {
if (typeof payload !== "object" && typeof payload !== "string") {
throw new Error("Payload must be an object or a string");
}
res.setHeader("Content-Type", "application/json");
const body = JSON.stringify(payload);
res.status(code).send(body);
res.end();
}
function errStringFromError(err) {
if (typeof err === "string") {
return err;
}
if (err instanceof Error) {
return err.message;
}
if (err) {
return String(err);
}
return "An unknown error occurred";
}
23 changes: 23 additions & 0 deletions dist/api/middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { respondWithError } from "./json.js";
import { getUser } from "../db/queries/users.js";
import { getAPIKey } from "./auth.js";
export function middlewareAuth(handler) {
return async (req, res) => {
try {
const apiKey = getAPIKey(req.headers);
if (!apiKey) {
respondWithError(res, 401, "Couldn't find api key");
return;
}
const user = await getUser(apiKey);
if (!user) {
respondWithError(res, 404, "Couldn't get user");
return;
}
handler(req, res, user);
}
catch (err) {
respondWithError(res, 500, "Couldn't authenticate user", err);
}
};
}
30 changes: 30 additions & 0 deletions dist/api/notes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { v4 as uuidv4 } from "uuid";
import { respondWithError, respondWithJSON } from "./json.js";
import { createNote, getNote, getNotesForUser } from "../db/queries/notes.js";
export async function handlerNotesGet(req, res, user) {
try {
const posts = await getNotesForUser(user.id);
respondWithJSON(res, 200, posts);
}
catch (err) {
respondWithError(res, 500, "Couldn't retrieve notes", err);
}
}
export async function handlerNotesCreate(req, res, user) {
try {
const { note } = req.body;
const noteId = uuidv4();
await createNote({
id: noteId,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
note,
userId: user.id,
});
const createdNote = await getNote(noteId);
respondWithJSON(res, 201, createdNote);
}
catch (err) {
respondWithError(res, 500, "Couldn't create note", err);
}
}
4 changes: 4 additions & 0 deletions dist/api/readiness.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { respondWithJSON } from "./json.js";
export function handlerReadiness(req, res) {
respondWithJSON(res, 200, { status: "ok" });
}
38 changes: 38 additions & 0 deletions dist/api/users.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import crypto from "crypto";
import { v4 as uuidv4 } from "uuid";
import { respondWithError, respondWithJSON } from "./json.js";
import { createUser, getUser } from "../db/queries/users.js";
export async function handlerUsersCreate(req, res) {
try {
const { name } = req.body;
const apiKey = generateRandomSHA256Hash();
const userId = uuidv4();
await createUser({
id: userId,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
name,
apiKey,
});
const user = await getUser(apiKey);
if (user) {
respondWithJSON(res, 201, user);
}
else {
respondWithError(res, 500, "Couldn't retrieve user");
}
}
catch (err) {
respondWithError(res, 500, "Couldn't create user", err);
}
}
export async function handlerUsersGet(req, res, user) {
respondWithJSON(res, 200, user);
}
function generateRandomSHA256Hash() {
// should we be using crypto.randomBytes instead of crypto.pseudoRandomBytes?
return crypto
.createHash("sha256")
.update(crypto.pseudoRandomBytes(32))
.digest("hex");
}
11 changes: 11 additions & 0 deletions dist/config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import dotenv from "dotenv";
dotenv.config();
export const config = {
api: {
port: process.env.PORT,
filepathRoot: "./src/assets",
},
db: {
url: process.env.DATABASE_URL,
},
};
23 changes: 23 additions & 0 deletions dist/db/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { drizzle } from "drizzle-orm/libsql";
import { config } from "../config.js";
import * as schema from "./schema.js";
let conn = undefined;
if (config.db.url) {
conn = drizzle({
connection: {
url: config.db.url,
},
schema: schema,
});
console.log("Connected to database!");
}
else {
console.log("DATABASE_URL environment variable is not set");
console.log("Running without CRUD endpoints");
}
export const db = conn;
export function assertDbConnection() {
if (!db) {
throw new Error("Database connection is not available");
}
}
24 changes: 24 additions & 0 deletions dist/db/queries/notes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { eq } from "drizzle-orm";
import { db, assertDbConnection } from "../index.js";
import { notesTable } from "../schema.js";
export async function createNote(note) {
assertDbConnection();
const rows = await db.insert(notesTable).values(note).returning();
if (rows.length === 0) {
throw new Error("Failed to create note");
}
return rows[0];
}
export async function getNote(id) {
assertDbConnection();
const rows = await db.select().from(notesTable).where(eq(notesTable.id, id));
return rows.length > 0 ? rows[0] : null;
}
export async function getNotesForUser(id) {
assertDbConnection();
const rows = await db
.select()
.from(notesTable)
.where(eq(notesTable.userId, id));
return rows;
}
19 changes: 19 additions & 0 deletions dist/db/queries/users.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { eq } from "drizzle-orm";
import { db, assertDbConnection } from "../index.js";
import { usersTable } from "../schema.js";
export async function createUser(user) {
assertDbConnection();
const rows = await db.insert(usersTable).values(user).returning();
if (rows.length === 0) {
throw new Error("Failed to create user");
}
return rows[0];
}
export async function getUser(apiKey) {
assertDbConnection();
const rows = await db
.select()
.from(usersTable)
.where(eq(usersTable.apiKey, apiKey));
return rows.length > 0 ? rows[0] : null;
}
22 changes: 22 additions & 0 deletions dist/db/schema.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { randomUUID } from "crypto";
import { sqliteTable, text } from "drizzle-orm/sqlite-core";
export const usersTable = sqliteTable("users", {
id: text("id", { length: 36 })
.primaryKey()
.$defaultFn(() => randomUUID()),
createdAt: text("created_at").notNull(),
updatedAt: text("updated_at").notNull(),
name: text("name").notNull(),
apiKey: text("api_key").notNull().unique(),
});
export const notesTable = sqliteTable("notes", {
id: text("id", { length: 36 })
.primaryKey()
.$defaultFn(() => randomUUID()),
createdAt: text("created_at").notNull(),
updatedAt: text("updated_at").notNull(),
note: text("note").notNull(),
userId: text("user_id")
.notNull()
.references(() => usersTable.id, { onDelete: "cascade" }),
});
37 changes: 37 additions & 0 deletions dist/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import express from "express";
import cors from "cors";
import path from "path";
import { config } from "./config.js";
import { db } from "./db/index.js";
import { middlewareAuth } from "./api/middleware.js";
import { handlerReadiness } from "./api/readiness.js";
import { handlerNotesCreate, handlerNotesGet } from "./api/notes.js";
import { handlerUsersCreate, handlerUsersGet } from "./api/users.js";
const __dirname = path.resolve();
if (!config.api.port) {
console.error("PORT environment variable is not set");
process.exit(1);
}
const app = express();
app.use(express.json());
app.use(cors({
origin: ["https://*", "http://*"],
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allowedHeaders: "*",
exposedHeaders: ["Link"],
credentials: false,
maxAge: 300,
}));
app.use("/", express.static(path.join(__dirname, config.api.filepathRoot)));
const v1Router = express.Router();
if (db) {
v1Router.post("/users", handlerUsersCreate);
v1Router.get("/users", middlewareAuth(handlerUsersGet));
v1Router.get("/notes", middlewareAuth(handlerNotesGet));
v1Router.post("/notes", middlewareAuth(handlerNotesCreate));
}
v1Router.get("/healthz", handlerReadiness);
app.use("/v1", v1Router);
app.listen(config.api.port, () => {
console.log(`Server is running on port: ${config.api.port}`);
});
1 change: 1 addition & 0 deletions node_modules/.bin/drizzle-kit

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions node_modules/.bin/esbuild

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions node_modules/.bin/mime

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions node_modules/.bin/nanoid

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions node_modules/.bin/rollup

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions node_modules/.bin/tsc

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions node_modules/.bin/tsserver

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions node_modules/.bin/tsx

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions node_modules/.bin/uuid

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions node_modules/.bin/vitest

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions node_modules/.bin/why-is-node-running

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading