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

Start moving from prisma to drizzle #188

Closed
wants to merge 20 commits into from
Closed
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
2 changes: 1 addition & 1 deletion app/components/device-card.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
CardHeader,
CardTitle,
} from "./ui/card";
import type { Device } from "@prisma/client";
import type { Device } from "db/schema";

interface DeviceCardProps {
device: Device;
Expand Down
8 changes: 4 additions & 4 deletions app/components/device-detail/device-detail-box.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ import {
useSubmit,
} from "@remix-run/react";
import Graph from "./graph";
import type { Prisma, Sensor } from "@prisma/client";
import type { DeviceWithSensors } from "types";
import Spinner from "../spinner";
import {
Accordion,
Expand Down Expand Up @@ -54,6 +52,8 @@ import { getArchiveLink } from "~/utils/device";
import { useBetween } from "use-between";
import { Alert, AlertDescription, AlertTitle } from "../ui/alert";
import { isMobile, isTablet, isBrowser } from "react-device-detect";
import type { Device, Sensor } from "db/schema";
import type { LastMeasurement } from "types";
import { Label } from "../ui/label";

export interface LastMeasurementProps {
Expand All @@ -62,7 +62,7 @@ export interface LastMeasurementProps {
}

export interface DeviceAndSelectedSensors {
device: DeviceWithSensors;
device: Device;
selectedSensors: Sensor[];
}

Expand Down Expand Up @@ -264,7 +264,7 @@ export default function DeviceDetailBox() {
{data.sensors.map((sensor: Sensor) => {
// dont really know why this is necessary - some kind of TypeScript/i18n bug?
const lastMeasurement =
sensor.lastMeasurement as Prisma.JsonObject;
sensor.lastMeasurement as LastMeasurement;
const value = lastMeasurement
? (lastMeasurement.value as string)
: undefined;
Expand Down
2 changes: 1 addition & 1 deletion app/components/header/nav-bar/index.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import type { Device } from "@prisma/client";
import { useState, useEffect, useRef, createContext } from "react";
import { useMap } from "react-map-gl";
import NavbarHandler from "./nav-bar-handler";
import { AnimatePresence, motion } from "framer-motion";
import { useTranslation } from "react-i18next";
import { SearchIcon, XIcon } from "lucide-react";
import type { Device } from "db/schema";

interface NavBarProps {
devices: Device[];
Expand Down
2 changes: 1 addition & 1 deletion app/components/header/nav-bar/nav-bar-handler.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import type { Device } from "@prisma/client";
import Search from "~/components/search";
import { Clock4Icon, Cog, Filter, IceCream2Icon } from "lucide-react";
import useKeyboardNav from "./use-keyboard-nav";
import { cn } from "~/lib/utils";
import FilterOptions from "./filter-options/filter-options";
import type { Device } from "db/schema";
import { PhenomenonSelect } from "./phenomenon-select/phenomenon-select";

interface NavBarHandlerProps {
Expand Down
25 changes: 12 additions & 13 deletions app/components/map/layers/cluster/box-marker.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import type { Device } from "@prisma/client";
import { Exposure } from "@prisma/client";
import { useMatches, useNavigate } from "@remix-run/react";
import { type Device } from "db/schema";
import { AnimatePresence, motion } from "framer-motion";
import { Box, Rocket } from "lucide-react";
import { useState } from "react";
Expand All @@ -14,12 +13,12 @@ interface BoxMarkerProps extends MarkerProps {
}

const getStatusColor = (device: Device) => {
if (device.status === "ACTIVE") {
if (device.exposure === Exposure.MOBILE) {
if (device.status === "active") {
if (device.exposure === "mobile") {
return "bg-blue-100";
}
return "bg-green-100";
} else if (device.status === "INACTIVE") {
} else if (device.status === "inactive") {
return "bg-gray-100";
} else {
return "bg-gray-100 opacity-50";
Expand All @@ -42,10 +41,10 @@ export default function BoxMarker({ device, ...props }: BoxMarkerProps) {
return 30;
}
// priority to active devices
if (device.status === "ACTIVE") {
if (device.status === "active") {
return 20;
}
if (device.status === "INACTIVE") {
if (device.status === "inactive") {
return 10;
}

Expand All @@ -63,12 +62,12 @@ export default function BoxMarker({ device, ...props }: BoxMarkerProps) {
<motion.div
className={cn(
"group absolute flex w-fit cursor-pointer items-center rounded-full bg-white p-1 text-sm shadow hover:z-10 hover:shadow-lg",
isFullZoom ? "-left-4 -top-4" : "-left-[10px] -top-[10px]"
isFullZoom ? "-left-4 -top-4" : "-left-[10px] -top-[10px]",
)}
onClick={() => {
if (compareMode) {
navigate(
`/explore/${matches[2].params.deviceId}/compare/${device.id}`
`/explore/${matches[2].params.deviceId}/compare/${device.id}`,
);
setCompareMode(false);
return;
Expand All @@ -81,19 +80,19 @@ export default function BoxMarker({ device, ...props }: BoxMarkerProps) {
<span
className={cn(
"relative rounded-full transition-colors",
isFullZoom && `${getStatusColor(device)} p-1`
isFullZoom && `${getStatusColor(device)} p-1`,
)}
>
{device.exposure === Exposure.MOBILE ? (
{device.exposure === "mobile" ? (
<Rocket className="text-black h-4 w-4" />
) : (
<Box className="text-black h-4 w-4" />
)}
{isFullZoom && device.status === "ACTIVE" ? (
{isFullZoom && device.status === "active" ? (
<div
className={cn(
"absolute left-0 top-0 h-full w-full animate-ping rounded-full opacity-50",
getStatusColor(device)
getStatusColor(device),
)}
/>
) : null}
Expand Down
8 changes: 4 additions & 4 deletions app/components/map/layers/cluster/cluster-layer.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import type { Device } from "@prisma/client";
import type {
GeoJsonProperties,
BBox,
Expand All @@ -13,6 +12,7 @@ import type { DeviceClusterProperties } from "~/routes/explore";
import DonutChartCluster from "./donut-chart-cluster";
import BoxMarker from "./box-marker";
import debounce from "lodash.debounce";
import type { Device } from "db/schema";

const DEBOUNCE_VALUE = 50;

Expand Down Expand Up @@ -49,7 +49,7 @@ export default function ClusterLayer({

// the viewport bounds and zoom level
const [bounds, setBounds] = useState(
mapRef?.getMap().getBounds().toArray().flat() as BBox
mapRef?.getMap().getBounds().toArray().flat() as BBox,
);
const [zoom, setZoom] = useState(mapRef?.getZoom() || 0);

Expand Down Expand Up @@ -99,7 +99,7 @@ export default function ClusterLayer({

const expansionZoom = Math.min(
supercluster.getClusterExpansionZoom(cluster.id as number),
20
20,
);

mapRef?.getMap().flyTo({
Expand All @@ -110,7 +110,7 @@ export default function ClusterLayer({
essential: true,
});
},
[mapRef, supercluster]
[mapRef, supercluster],
);

const clusterMarker = useMemo(() => {
Expand Down
8 changes: 4 additions & 4 deletions app/components/map/layers/mobile/mobile-box-layer.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import type { Sensor } from "@prisma/client";
import {
featureCollection,
lineString,
Expand All @@ -10,6 +9,7 @@ import { useEffect, useState } from "react";
import { Layer, Source, useMap } from "react-map-gl";
import bbox from "@turf/bbox";
import { HIGH_COLOR, LOW_COLOR, createPalette } from "./color-palette";
import type { Sensor } from "db/schema";

const FIT_PADDING = 50;
const BOTTOM_BAR_HEIGHT = 400;
Expand Down Expand Up @@ -45,7 +45,7 @@ export default function MobileBoxLayer({
minValue,
maxValue,
minColor as string,
maxColor as string
maxColor as string,
);

// generate points from the sensor data
Expand All @@ -55,7 +55,7 @@ export default function MobileBoxLayer({
value: Number(measurement.value),
createdAt: new Date(measurement.createdAt),
color: palette(Number(measurement.value)).hex(),
})
}),
);

if (points.length === 0) return;
Expand All @@ -65,7 +65,7 @@ export default function MobileBoxLayer({
const lines = multiLineString([line.geometry.coordinates]);

setSourceData(
featureCollection<Point | MultiLineString>([...points, lines])
featureCollection<Point | MultiLineString>([...points, lines]),
);
}, [maxColor, minColor, sensor.data]);

Expand Down
2 changes: 1 addition & 1 deletion app/components/map/layers/mobile/mobile-box-view.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { Sensor } from "@prisma/client";
import MobileBoxLayer from "./mobile-box-layer";
import { HIGH_COLOR, LOW_COLOR } from "./color-palette";
import { useEffect, useRef, useState } from "react";
import type { Sensor } from "db/schema";

export default function MobileBoxView({ sensors }: { sensors: Sensor[] }) {
return (
Expand Down
7 changes: 4 additions & 3 deletions app/components/mydevices/dt/columns.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@
import type { ColumnDef } from "@tanstack/react-table";
import { ArrowUpDown, ClipboardCopy } from "lucide-react";
import { Button } from "@/components/ui/button";
import type { Exposure } from "@prisma/client";
import type { Device } from "db/schema";

// TODO: maybe it´s possible to use the drizzle Device type
export type SenseBox = {
id: string;
name: string;
exposure: Exposure;
// model: string;
exposure: Device["exposure"];
model: Device["model"];
};

export const columns: ColumnDef<SenseBox>[] = [
Expand Down
40 changes: 11 additions & 29 deletions app/db.server.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,25 @@
import { PrismaClient } from "@prisma/client";
import { drizzle, type PostgresJsDatabase } from "drizzle-orm/postgres-js";
import postgres from "postgres";
import invariant from "tiny-invariant";
import * as schema from "../db/schema";

let prisma: PrismaClient;
let drizzleClient: PostgresJsDatabase<typeof schema>;

declare global {
var __db__: PrismaClient;
var __db__: PostgresJsDatabase<typeof schema>;
}

// this is needed because in development we don't want to restart
// the server with every change, but we want to make sure we don't
// create a new connection to the DB with every change either.
// in production we'll have a single connection to the DB.
if (process.env.NODE_ENV === "production") {
prisma = getClient();
drizzleClient = getClient();
} else {
if (!global.__db__) {
global.__db__ = getClient();
}
prisma = global.__db__;
drizzleClient = global.__db__;
}

function getClient() {
Expand All @@ -26,36 +28,16 @@ function getClient() {

const databaseUrl = new URL(DATABASE_URL);

const isLocalHost = databaseUrl.hostname === "localhost";
console.log(`🔌 setting up drizzle client to ${databaseUrl.host}`);

const PRIMARY_REGION = isLocalHost ? null : false;

const isReadReplicaRegion = !PRIMARY_REGION;

if (!isLocalHost) {
databaseUrl.host = `${databaseUrl.host}`;
if (!isReadReplicaRegion) {
// 5433 is the read-replica port
databaseUrl.port = "5433";
}
}

console.log(`🔌 setting up prisma client to ${databaseUrl.host}`);
// NOTE: during development if you change anything in this function, remember
// that this only runs once per server restart and won't automatically be
// re-run per request like everything else is. So if you need to change
// something in this file, you'll need to manually restart the server.
const client = new PrismaClient({
datasources: {
db: {
url: databaseUrl.toString(),
},
},
});
// connect eagerly
client.$connect();
const queryClient = postgres(DATABASE_URL);
const client = drizzle(queryClient, { schema });

return client;
}

export { prisma };
export { drizzleClient };
4 changes: 3 additions & 1 deletion app/lib/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export const hasObjPropMatchWithPrefixKey = (
object: Object,
prefixes: string[]
prefixes: string[],
) => {
const keys = Object.keys(object);
for (const key of keys) {
Expand All @@ -13,6 +13,8 @@ export const hasObjPropMatchWithPrefixKey = (
return false;
};

// TODO: can be removed after switching to drizzle
// enums will be named lower case
export const exposureHelper = (exposure: string) => {
switch (exposure) {
case "mobile":
Expand Down
Loading