Advertisement
Guest User

Untitled

a guest
Jun 2nd, 2022
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { assert } from 'console'
  2. import fastify from 'fastify'
  3. import { json } from 'stream/consumers'
  4. import allTodos from './todos.json' assert { type: "json" }
  5. import fs from 'fs'
  6. const server = fastify()
  7.  
  8. var deleteall = {
  9.   todos: []
  10. }
  11. /*  Append string to file instead of overwriting it.
  12. fs.readFile('todos.json', 'utf8', function readFileCallback(err, data){
  13.   if (err){
  14.       console.log(err);
  15.   } else {
  16.   obj = JSON.parse(data); //now it an object
  17.   obj.table.push({id: 2, square:3}); //add some data
  18.   json = JSON.stringify(obj); //convert it back to json
  19.   fs.writeFile('todos.json', json, 'utf8', callback); // write it back
  20. }});
  21. */
  22.  
  23. server.get('/', async (request, reply) => {
  24.   return 'Hey, available endpoints: /getall, /deleteall, /edit, /add, /delete\n'
  25. })
  26.  
  27.  
  28. // Get all ToDos endpoint, this is the main endpoint, it'll get more requests than other endpoints.
  29. server.get('/getall', async (request, reply) => {
  30.   return allTodos.todos.join(", ")
  31. })
  32.  
  33. server.get('/deleteall', async (request, reply) => {
  34.   var json = JSON.stringify(deleteall);
  35.   fs.writeFile('todos.json', json, 'utf8', callback);
  36.   return 'File overwritten.'
  37. })
  38.  
  39.  
  40. server.listen(8080, (err, address) => {
  41.   if (err) {
  42.     console.error(err)
  43.     process.exit(1)
  44.   }
  45.   console.log(`Server listening at ${address}`)
  46. })
  47.  
  48. function callback(arg0: string, json: string, arg2: string, callback: any) {
  49.   throw new Error('Function not implemented.')
  50. }
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement