Skip to content
Permalink
Browse files
List Display and Non-Locking Geo
  • Loading branch information
aa7401 committed Apr 13, 2020
1 parent 882684e commit 9cfb315e347f48708816934d9d4011181a6f1507
Show file tree
Hide file tree
Showing 7 changed files with 176 additions and 29 deletions.
@@ -12,6 +12,7 @@ const defaultPort = 8080
const port = process.env.PORT || defaultPort
const dbName = 'website.db'
const User = require('./modules/user')
const List = require('./modules/list')

app.use(staticDir('public'))

@@ -61,5 +62,40 @@ router.get('/login', async ctx => {
}
})

router.post('/lists', koaBody, async ctx => {
console.log('---------------------------------------------------------------')
console.log('POST /lists')
const list = await new List(dbName)
try {
const body = typeof ctx.request.body === 'string' ? JSON.parse(ctx.request.body) : ctx.request.body
console.log(body)
const header = ctx.request.headers.authorization
console.log(header)
body.id = await list.add(header, body.listname, body.description)
ctx.status = 201
ctx.body = {status: 'success', msg: 'list added', data: ctx.body}
} catch(err) {
ctx.status = 422
ctx.body = {status: "error", msg: err.message}
} finally {
list.tearDown()
}
})

router.get('/lists', async ctx => {
console.log('---------------------------------------------------------------')
console.log('GET /lists')
const list = await new List(dbName)
try {
const lists = await list.getLists(ctx.request.headers.authorization)
console.log(lists)
ctx.status = 200
ctx.body = {status: 'success', msg: 'lists found', data: lists}
} catch(err) {
ctx.status = 422
ctx.body = {status: "error", msg: err.message}
}
})

app.use(router.routes())
module.exports = app.listen(port, () => console.log(`listening on port ${port}`))
@@ -0,0 +1,61 @@

const sqlite = require('sqlite-async')
const atob = require('atob')

module.exports = class List {

constructor(dbName = ':memory:') {
return (async() => {
this.db = await sqlite.open(dbName)
// we need this table to store the user accounts
const sql = 'CREATE TABLE IF NOT EXISTS lists\
(id INTEGER PRIMARY KEY AUTOINCREMENT,\
userid TEXT, listname TEXT, description TEXT,\
date TEXT DEFAULT CURRENT_TIMESTAMP);'
await this.db.run(sql)
return this
})()
}

async add(token, listname, description) {
try {
console.log(token)
const hash = token.substring(6) //removes the Basic_ bit
console.log(hash)
const str = atob(hash)
console.log(str)
const username = str.split(':')[0]
console.log(username)
const sql = `INSERT INTO lists(userid, listname, description)\
VALUES("${username}", "${listname}", "${description}")`
console.log(sql)
const recordID = await this.db.run(sql)
console.log(recordID.lastID)
return recordID.lastID
// return 42
} catch(err) {
console.log(err.message)
throw err
}
}

async getLists(token) {
try {
const hash = token.substring(6) //removes the Basic_ bit
const str = atob(hash)
const username = str.split(':')[0]
const sql = `SELECT * FROM lists WHERE userid="${username}" ORDER BY date DESC;`
console.log(sql)
const lists = await this.db.all(sql)
console.log(lists)
return lists
} catch(err) {
console.log(err.message)
throw err
}
}

async tearDown() {
await this.db.close()
}
}
@@ -46,16 +46,14 @@ export function showMessage(message) {
}

export function getLocation() {
return new Promise( (resolve, reject) => {
console.log('getting location')
if(navigator.geolocation) {
console.log('location supported')
navigator.geolocation.getCurrentPosition( position => {
console.log(position)
resolve({lat: position.coords.latitude, lon: position.coords.longitude})
})
} else {
return reject('geolocation not supported')
}
})
if(navigator.geolocation) {
console.log('location supported')
navigator.geolocation.getCurrentPosition( position => {
const pos = position.coords
const locString = `lat: ${pos.latitude}, lon: ${pos.longitude}`
document.getElementById('location').innerHTML = `${locString}<br />&nbsp;`
})
} else {
console.log('geolocation not supported')
}
}
@@ -3,14 +3,36 @@ import { getCookie, login, showMessage } from '../core.js'

export async function setup() {
try {
console.log('MAIN SCRIPT')
await login()
document.querySelector('h1').innerText = 'Home Page'
displayLists()
document.querySelector('h1').innerText = 'My Lists'
document.querySelector('main > button').addEventListener('click', event => {
console.log('adding a new note')
document.querySelector('main section').classList.remove('hidden')
// await displayLists()
})
} catch(err) {
showMessage(err.message)
window.location.href = '/#login'
}
}

async function displayLists() {
console.log('DISPLAY LISTS')
// const request= new Request('/lists')
// request.url = '/lists'
const options = { headers: { Authorization: getCookie('authorization') } }
const response = await fetch('/lists',options)
// const head = new Headers({authorization: getCookie('authorization')})
// const options = { method: 'post', headers: head }
// request.headers = head
const json = await response.json()
// console.log(await response.json())
const page = document.querySelector('main')
for(const list of json.data) {
console.log(list)
const section = document.createElement('article')
section.innerHTML = `<h2>${list.listname}</h2><p>${list.description}</p><button>Show list</button>`
page.appendChild(section)
}
}
@@ -13,7 +13,7 @@ let geoID

// event triggered when the page first loads, triggers the 'hashchange' event
window.addEventListener('DOMContentLoaded', async event => {
geoID = await navigator.geolocation.watchPosition(updateLocation)
geoID = await navigator.geolocation.watchPosition(getLocation)
loadPage()
})

@@ -36,20 +36,14 @@ function toggleOnlineIndicator(event) {
}
}

/* this function is called to update the location displayed in the footer */
async function updateLocation() {
const location = await getLocation()
const locString = `lat: ${location.lat}, lon: ${location.lon}`
document.getElementById('location').innerHTML = `${locString}<br />&nbsp;`
}

async function loadPage() {
try {
await updateLocation()
getLocation()
// the 'name' of the page is the name in the fragment without the # character
// if there is no fragment/hash, assume we want to load the home page (ternary operator)
console.log(typeof location.hash)
const pageName = location.hash ? location.hash.replace('#', '') : 'home'
console.log('location updated')
// load the html page that matches the fragment and inject into the page DOM
document.querySelector('main').innerHTML = await (await fetch(`./views/${pageName}.html`)).text()
// dynamically importing the code module who's name matches the page name
@@ -132,8 +132,9 @@ input[type="text"], input[type="email"], input[type="password"], textarea, selec
}
main > button {
position: absolute;
bottom: 5.5em;
right: 1em;
z-index: 2;
bottom: 0.5em;
right: 0.5em;
}

main > section {
@@ -155,14 +156,50 @@ main > section button {
float: right;
}

article {
background-color: #CCCC;
margin-bottom: 0.5em;
padding: 1em;
padding-bottom: 3em;
}

article > h2 {
margin: 0;
padding: 0;
/* display: inline-block; */
font-size: 1.2em;
/* background-color: blue; */
height: 2em;
flex-grow: 1;
}

article > p {
margin: 0;
padding: 0;
/* display: inline-block; */
/* background-color: yellow; */
height: 2em;
flex-grow: 2;
}

article > button {
margin: 0;
display: block;
height: 2em;
flex-grow: 1;
float: right;
}

footer {
position: absolute;
position: fixed;
bottom: 0;
left: 0;
background-color: #DDD;
width: 100%;
padding: 0;
margin: 0;
padding-left: 0.3em;
padding-top: 0.5em;
}

footer > p#device, footer > p#resolution, footer > p#connectivity {
@@ -1,11 +1,10 @@

<p>Home Page</p>
<button>Add list</button>

<section class="hidden">
<form name="note">
<h2>Add Note</h2>
<p><label for="name">Name</label><br /><input type="text" name="name" placeholder="name of note" /></p>
<h2>New List</h2>
<p><label for="name">Name</label><br /><input type="text" name="name" placeholder="name of list" /></p>
<p><label for="pass">Description</label><br /><textarea></textarea></p>
<p><button type="submit">Add</button></p>
</form>

0 comments on commit 9cfb315

Please sign in to comment.