{"size": 1124, "ext": "js", "max_stars_repo_path": "07-nodejs/Koa/resource/index.js", "max_stars_repo_name": "WuChenDi/KnowledgePoint", "max_stars_repo_stars_event_min_datetime": "2018-07-27T07:53:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-14T01:07:02.000Z", "max_issues_repo_path": "07-nodejs/Koa/resource/index.js", "max_issues_repo_name": "WuChenDi/KnowledgePoint", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "07-nodejs/Koa/resource/index.js", "max_forks_repo_name": "WuChenDi/KnowledgePoint", "max_forks_repo_forks_event_min_datetime": "2018-08-23T01:28:18.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-14T01:05:39.000Z"}
{"max_stars_count": 5, "max_issues_count": null, "max_forks_count": 2, "avg_line_length": 20.0714285714, "max_line_length": 54, "alphanum_fraction": 0.6174377224}
const Koa = require("koa");
const Router = require("koa-router");
const cors = require("@koa/cors");
const koaBody = require("koa-body");
const json = require("koa-json");

const app = new Koa();
const router = new Router();

router.prefix("/api");

router.get("/", (ctx) => {
	console.log(ctx);
	console.log(ctx.request);
	ctx.body = "hello koa";
});

router.get("/api", (ctx) => {
	// console.log(ctx);
	// console.log(ctx.request);
	const params = ctx.request.query;
	console.log(params);
	// ctx.body = "hello Api";
	ctx.body = {
		name: params.name,
		age: params.age,
	};
});

router.get("/async", async (ctx) => {
	ctx.body = await new Promise((resolve) => {
		setTimeout(() => {
			resolve("hello async 2s later");
		}, 2000);
	});
});

router.post("/post", async (ctx) => {
	let { body } = ctx.request;
	console.log(body);
	console.log(ctx.request);
	ctx.body = {
		...body,
	};
});

app.use(koaBody());
app.use(cors());
app.use(json({ pretty: false, param: "pretty" }));
// request, method, respond
// api url function router
// ctx, async
app.use(router.routes()).use(router.allowedMethods());

app.listen(3000);
