Advertisement
Guest User

koa.js

a guest
Feb 18th, 2020
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.86 KB | None | 0 0
  1. const Koa = require('koa');
  2. const Router = require('koa-router');
  3. const { Pool } = require('pg');
  4. const koaBody = require('koa-bodyparser')();
  5. const cors = require('kcors');
  6.  
  7. // db pool
  8. const pool = new Pool({
  9. user: 'weather',
  10. host: 'db',
  11. database: 'weather_db',
  12. password: 'weather',
  13. });
  14.  
  15. // The port that this server will run on, defaults to 9000
  16. const port = process.env.PORT || 9000;
  17. // Instantiate a Koa server
  18. const app = new Koa();
  19. app.use(cors());
  20.  
  21. // Instantiate routers
  22. const weather = new Router();
  23.  
  24. // Define API path
  25. const apiPath = '/v1';
  26. const weatherPath = `${apiPath}/weather`;
  27.  
  28. // async/await - check out a client
  29. weather.get(apiPath, async (ctx) => {
  30. const client = await pool.connect();
  31. try {
  32. const data = await client.query('SELECT NOW() as now');
  33. client.release();
  34. // Tell the HTTP response that it contains JSON data encoded in UTF-8
  35. ctx.type = 'application/json; charset=utf-8';
  36. ctx.body = data.rows;
  37. } catch (error) {
  38. console.error('Error occurred:', error);
  39. ctx.throw(500, error);
  40. }
  41. });
  42.  
  43. // get last 50
  44. weather.get(weatherPath, async (ctx) => {
  45. const client = await pool.connect();
  46. try {
  47. const sql=`SELECT device_id, date_time, data from weather ORDER BY id DESC LIMIT 50`;
  48. const data = await client.query(sql);
  49. ctx.type = 'application/json; charset=utf-8';
  50. ctx.body = data.rows;
  51. } catch (error) {
  52. console.error('Error occurred:', error);
  53. ctx.throw(500, error);
  54. } finally {
  55. client.release(); // release client back to pool
  56. }
  57. });
  58.  
  59. // get lastest
  60. weather.get(`${weatherPath}/latest`, async (ctx) => {
  61. const client = await pool.connect();
  62. try {
  63. const sql=`SELECT device_id, date_time, data from weather ORDER BY id DESC LIMIT 1`;
  64. const data = await client.query(sql);
  65. ctx.type = 'application/json; charset=utf-8';
  66. ctx.body = data.rows;
  67. } catch (error) {
  68. console.error('Error occurred:', error);
  69. ctx.throw(500, error);
  70. } finally {
  71. client.release(); // release client back to pool
  72. }
  73. });
  74.  
  75. // insert new data
  76. weather.post(weatherPath, koaBody, async (ctx) => {
  77. const { device_id } = ctx.request.body;
  78. const data = ctx.request.body.data;
  79.  
  80. const sql = 'INSERT INTO weather(device_id, data) VALUES($1, $2)';
  81. const values = [device_id, data];
  82.  
  83. const client = await pool.connect();
  84. try {
  85. await client.query(sql, values);
  86. ctx.type = 'application/json; charset=utf-8';
  87. ctx.status = 201;
  88. } catch (error) {
  89. console.error('Error occurred:', error);
  90. ctx.throw(500, error);
  91. } finally {
  92. client.release(); // release client back to pool
  93. }
  94. });
  95.  
  96. app.use(weather.routes());
  97. app.use(weather.allowedMethods());
  98.  
  99. // Start the server and keep listening on port until stopped
  100. app.listen(port);
  101.  
  102. console.log(`App listening on port ${port}`);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement