Skip to content

Instantly share code, notes, and snippets.

@jbergant
Created June 9, 2020 07:47
Show Gist options
  • Select an option

  • Save jbergant/7a41b3cb3ca192954cb0736fef82d960 to your computer and use it in GitHub Desktop.

Select an option

Save jbergant/7a41b3cb3ca192954cb0736fef82d960 to your computer and use it in GitHub Desktop.
Deno simple API for IT courses
import { Application, Router } from "https://deno.land/x/oak/mod.ts";
const env = Deno.env.toObject();
const PORT = Number(env.PORT) || 8000;
const HOST = env.HOST || "localhost";
interface Course {
title: string;
author: string;
rating: number;
}
let courses: Array<Course> = [
{
title: "Chatbots",
author: "Jana Bergant",
rating: 9,
},
{
title: "Google Assistant app",
author: "Jana Bergant",
rating: 8,
},
{
title: "Blog with Jekyll",
author: "Jana Bergant",
rating: 8,
},
];
export const getCourses = ({ response }: { response: any }) => {
response.body = courses;
};
export const getCourse = ({
params,
response,
}: {
params: {
title: string;
};
response: any;
}) => {
const course = courses.filter((course) => course.title === params.title);
if (course.length) {
response.status = 200;
response.body = course[0];
return;
}
response.status = 400;
response.body = { msg: `Cannot find course ${params.title}` };
};
export const addCourse = async ({
request,
response,
}: {
request: any;
response: any;
}) => {
const body = await request.body();
const course: Course = body.value;
courses.push(course);
response.body = { msg: "OK" };
response.status = 200;
};
export const updateCourse = async ({
params,
request,
response,
}: {
params: {
title: string;
};
request: any;
response: any;
}) => {
const temp = courses.filter((existingDCourse) =>
existingDCourse.title === params.title
);
const body = await request.body();
const { rating }: { rating: number } = body.value;
if (temp.length) {
temp[0].rating = rating;
response.status = 200;
response.body = { msg: "OK" };
return;
}
response.status = 400;
response.body = { msg: `Cannot find course ${params.title}` };
};
export const deleteCourse = ({
params,
response,
}: {
params: {
title: string;
};
response: any;
}) => {
const lengthBefore = courses.length;
courses = courses.filter((course) => course.title !== params.title);
if (courses.length === lengthBefore) {
response.status = 400;
response.body = { msg: `Cannot find course ${params.title}` };
return;
}
response.body = { msg: "OK" };
response.status = 200;
};
const router = new Router();
router
.get("/courses", getCourses)
.get("/courses/:title", getCourse)
.post("/courses", addCourse)
.put("/courses/:title", updateCourse)
.delete("/courses/:title", deleteCourse);
const app = new Application();
app.use(router.routes());
app.use(router.allowedMethods());
console.log(`Listening on port ${PORT}...`);
await app.listen(`${HOST}:${PORT}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment