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-API-Template/index.js
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
79 lines (66 sloc)
1.95 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
/* index.js */ | |
import { Application, Router, Status, send } from 'https://deno.land/x/oak/mod.ts' | |
// status codes https://deno.land/std@0.82.0/http/http_status.ts | |
import { checkAuth } from './modules/accounts.js' | |
// import { errorHandler, setHeaders, staticFiles } from './modules/util.js' | |
import { setHeaders } from './modules/util.js' | |
const port = 8080 | |
const app = new Application() | |
const router = new Router() | |
router.get('/', async context => { | |
const data = await Deno.readTextFile('static/index.html') | |
context.response.body = data | |
}) | |
router.get('/films', async context => { | |
const data = { status: 'test' } | |
context.response.body = JSON.stringify(data, null, 2) | |
}) | |
.get("/(.*)", async context => { | |
const data = await Deno.readTextFile('static/404.html') | |
context.response.body = data | |
}) | |
// checks if file exists | |
async function fileExists(path) { | |
try { | |
const stats = await Deno.lstat(path) | |
return stats && stats.isFile | |
} catch(e) { | |
if (e && e instanceof Deno.errors.NotFound) { | |
return false | |
} else { | |
throw e | |
} | |
} | |
} | |
async function staticFiles(context, next) { | |
const path = `${Deno.cwd()}/static${context.request.url.pathname}` | |
const isFile = await fileExists(path) | |
if (isFile) { | |
// file exists therefore we can serve it | |
await send(context, context.request.url.pathname, { | |
root: `${Deno.cwd()}/static` | |
}) | |
} else { | |
await next() | |
} | |
} | |
async function errorHandler(context, next) { | |
try { | |
const method = context.request.method | |
const path = context.request.url.pathname | |
console.log(`${method} ${path}`) | |
await next() | |
} catch (err) { | |
console.log(err) | |
context.response.status = Status.InternalServerError | |
const msg = { err: err.message } | |
context.response.body = JSON.stringify(msg, null, 2) | |
} | |
} | |
app.use(staticFiles) | |
app.use(router.routes()) | |
app.use(router.allowedMethods()) | |
app.use(setHeaders) | |
app.use(errorHandler) | |
app.addEventListener('listen', ({ port }) => console.log(`listening on port: ${port}`) ) | |
await app.listen({ port }) |