Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: check grid intensity on middleware #26

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
const { nextUrl: url, geo } = request;
const country = geo.country || 'US';
const latitude = geo.latitude || '37.3719';
const longitude = geo.longitude || '-79.8164';

url.searchParams.set('country', country);
url.searchParams.set('latitude', latitude);
url.searchParams.set('longitude', longitude);

return NextResponse.rewrite(url);
}

export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - static (static files)
* - favicon.ico (favicon file)
*/
'/((?!api|static|favicon.ico).*)',
],
};
24 changes: 23 additions & 1 deletion pages/index.jsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,36 @@
import Head from 'next/head';
import BackgroundColor from '../src/components/background-color';
import calculateCarbonIntensity from '../src/base/services/calculate-carbon-intensity';

export default function IndexPage() {
export default function IndexPage(props) {
return (
<>
<Head>
<title>Sustainable UI</title>
<meta name="description" content="Sustainable UI in NextJS" />
</Head>
<pre style={{ color: 'black' }}>{JSON.stringify(props, null, 2)}</pre>
<BackgroundColor />
</>
);
}

export async function getServerSideProps(ctx) {
const { country, latitude, longitude } = ctx.query;

let gridCarbonIntensity = null;
try {
gridCarbonIntensity = await calculateCarbonIntensity({ lon: longitude, lat: latitude });
} catch (err) {
console.error(err);
}

return {
props: {
country,
latitude,
longitude,
gridCarbonIntensity,
},
};
}
37 changes: 37 additions & 0 deletions src/base/services/calculate-carbon-intensity.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import AZURE_REGIONS from '../../../pages/api/azure-regions.json';

const R = 6371e3;

export default async function calculateCarbonIntensity(cords) {
const closestAzureRegion = getClosestAzureRegion({ lat: cords.lat, lon: cords.lon }, AZURE_REGIONS);

const res = await fetch(
`https://carbon-aware-api.azurewebsites.net/emissions/bylocation?location=${closestAzureRegion}`,
);
return res.json();
}

function getClosestAzureRegion(userCoords, azureRegions) {
const azureRegionsDistances = azureRegions.map(azureRegion =>
distance(userCoords, {
lat: azureRegion.Latitude,
lon: azureRegion.Longitude,
}),
);

const closestAzureRegionDistance = Math.min(...azureRegionsDistances);

const closestAzureRegionIndex = azureRegionsDistances.findIndex(
azureRegionsDistance => azureRegionsDistance === closestAzureRegionDistance,
);

return azureRegions[closestAzureRegionIndex].RegionName;
}

function distance({ lat: lat1, lon: lon1 }, { lat: lat2, lon: lon2 }) {
const φ1 = (lat1 * Math.PI) / 180;
const φ2 = (lat2 * Math.PI) / 180;
const Δλ = ((lon2 - lon1) * Math.PI) / 180;

return Math.acos(Math.sin(φ1) * Math.sin(φ2) + Math.cos(φ1) * Math.cos(φ2) * Math.cos(Δλ)) * R;
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
left: 0;
height: 100vh;
width: 100vw;
z-index: 0;
z-index: -1;
}

.lowContainer {
Expand Down