Firebaseで開発する

1. Firebaseでプロジェクトを作成
プロジェクト名: typescript-hpscript
google analytics: off

2.Realtime database
create database
location: United States(us-central)
start in test mode

edit rule

{
  "rules": {
    ".read": true,
    ".write": true,
    "boards": {
      ".indexOn":["posted"]
    }
  }
}

index.html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
	<script src="main.js"></script>
</head>
<body>
	<h1 class="bg-primary text-white p-2">Board</h1>
	<div class="container">
		<h2>send message:</h2>
		<div class="alert alert-primary">
			<div>
				<label>your nickname:</label>
				<input type="text" id="nickname" class="form-control form-control-sm"/>
			</div>
			<div>
				<label>message:</label>
				<input type="text" class="form-control" id="message"/>
			</div>
			<button class="btn btn-primary mt-2" id="btn">
			fetch</button>
			</div>
			<table class="table mb-4" id="table"></table>
			<div class="text-center">
				<button class="btn btn-danger mb-4" id="delete">delete all</button></div>
	</div>
</body>
</html>

index.ts

let nickname: HTMLInputElement
let message:HTMLInputElement
let table:HTMLTableElement
const url = ‘https://typescript-hpscript.firbaseio.com/boards.json’

function doAction(){
const data = {
nickname: nickname.value,
message: message.value,
posted: new Date().getTime()
}
sendData(url, data)
}

function doDelete():void {
fetch(url, {
method: ‘DELETE’
}).then(res=> {
console.log(res.statusText)
getData(url)
})
}

function sendData(url:string, data:object){
fetch(url, {
method: ‘POST’,
mode: ‘cors’,
headers: {
‘Content-Type’:’application/json’
},
body: JSON.stringify(data)
}).then(res=>{
console.log(res.statusText)
getData(url)
})
}

function getData(url:string){
fetch(url).then(res=>res.json()).then(re=> {
let result = `

Message Nickname posted `
let tb = ”
for(let ky in re){
let item = re[ky]
tb = ‘

‘ + item[‘message’] + ‘ ‘
+ item[‘nickname’] + ‘ ‘
+ new Date(item[‘posted’]).toLocaleString()
+ ‘

‘ + tb
}
result += tb + ‘


table.innerHTML = result
})
}

window.addEventListener(‘load’, ()=> {
message = document.querySelector(‘#message’)
nickname = document.querySelector(‘#nickname’)
table = document.querySelector(‘#table’)

const btn : HTMLButtonElement = document.querySelector(‘#btn’)
btn.onclick = doAction
const del :HTMLButtonElement =
document.querySelector(‘#delete’)
del.onclick = doDelete
getData(url)
})
[/code]

ちょっと上手くいかんな