Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Codio-Deno-SPA-Template/api.js
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
65 lines (55 sloc)
1.93 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* api.js */ | |
import { Router } from 'https://deno.land/x/oak@v6.5.1/mod.ts' | |
import { extractCredentials, saveFile } from './modules/util.js' | |
import { login, register } from './modules/accounts.js' | |
const router = new Router() | |
// the routes defined here | |
router.get('/', async context => { | |
const data = await Deno.readTextFile('static/index.html') | |
context.response.body = data | |
}) | |
router.get('/accounts', async context => { | |
console.log('GET /accounts') | |
const token = context.request.headers.get('Authorization') | |
console.log(`auth: ${token}`) | |
try { | |
const credentials = extractCredentials(token) | |
console.log(credentials) | |
const username = await login(credentials) | |
console.log(`username: ${username}`) | |
context.response.body = JSON.stringify({ status: 'success', data: { username } }, null, 2) | |
} catch(err) { | |
context.response.status = 401 | |
context.response.body = JSON.stringify({ status: 'unauthorised', msg: err.msg }) | |
} | |
}) | |
router.post('/accounts', async context => { | |
console.log('POST /accounts') | |
const body = await context.request.body() | |
const data = await body.value | |
console.log(data) | |
await register(data) | |
context.response.status = 201 | |
context.response.body = JSON.stringify({ status: 'success', msg: 'account created' }) | |
}) | |
router.post('/files', async context => { | |
console.log('POST /files') | |
try { | |
const token = context.request.headers.get('Authorization') | |
console.log(`auth: ${token}`) | |
const body = await context.request.body() | |
const data = await body.value | |
console.log(data) | |
saveFile(data.base64, data.user) | |
context.response.status = 201 | |
context.response.body = JSON.stringify({ status: 'success', msg: 'file uploaded' }) | |
} catch(err) { | |
context.response.status = 401 | |
context.response.body = JSON.stringify({ status: 'unauthorised', msg: err.msg }) | |
} | |
}) | |
router.get("/(.*)", async context => { | |
const data = await Deno.readTextFile('static/404.html') | |
context.response.body = data | |
}) | |
export default router |