route.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { NextResponse } from "next/server";
  2. import automation from "data/automation.json";
  3. import { pick } from "lib/utils";
  4. const get = (url) => {
  5. return fetch(url, {
  6. headers: { "Content-Type": "application/json" },
  7. redirect: "follow",
  8. cache: "no-store",
  9. mode: "cors"
  10. })
  11. .then((resp) => resp && resp.json())
  12. .then((result) => result);
  13. };
  14. const status = ({ client }) => {
  15. let url = `http://${client}/json/state`;
  16. return get(url)
  17. .then((resp) => resp?.state || resp || {})
  18. .then((state) => pick(state, ["on", "bri", "ps", "pl", "udpn"]))
  19. .then((state) => ({ ...state, client }))
  20. .catch((err) => ({ error: err.message }));
  21. };
  22. export async function GET(req, { params }) {
  23. let promises = [];
  24. let id = 1;
  25. try {
  26. if (!id) throw new Error("No id specified");
  27. let clients = (automation?.[id] && Object.keys(automation?.[id])) || [];
  28. if (!clients) throw new Error("No clients for id", id);
  29. for (let client of clients) {
  30. promises.push(status({ id, client, ...automation?.[id]?.[client] }));
  31. }
  32. } catch (err) {
  33. return NextResponse.json({ error: err?.message }, { status: 500 });
  34. }
  35. return Promise.allSettled(promises)
  36. .then((results) => {
  37. return NextResponse.json(results?.map((o) => o?.value));
  38. })
  39. .catch((err) => {
  40. return NextResponse.json({ error: err?.message }, { status: 500 });
  41. });
  42. }