Skip to content

Commit

Permalink
Merge pull request #91 from BuidlGuidl/feat/add-mongoose
Browse files Browse the repository at this point in the history
Feat/add mongoose
  • Loading branch information
escottalexander authored Apr 11, 2024
2 parents 642f0d5 + bec8384 commit aa715c0
Show file tree
Hide file tree
Showing 12 changed files with 220 additions and 70 deletions.
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@ Static data set: https://github.com/opensource-observer/insights/blob/main/commu

### Database setup

This project uses [MongoDB](https://www.mongodb.com/) for a database. To run the project locally, a value is needed for the `MONGODB_URI` env variable that points to a development database named `impact_calculator`, running locally or hosted with [MongoDB Atlas](https://www.mongodb.com/docs/atlas/getting-started/).
This project uses [MongoDB](https://www.mongodb.com/) for a database. To run the project locally, a value is needed for the `MONGODB_URI` env variable, running locally or hosted with [MongoDB Atlas](https://www.mongodb.com/docs/atlas/getting-started/). Your `MONGODB_URI` should be in this format:
```
mongodb+srv://USERNAME:PASSWORD@SERVER/DATABASE_NAME
```

# Built with 🏗 Scaffold-ETH 2

Expand Down
1 change: 1 addition & 0 deletions packages/nextjs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
"eslint-config-next": "^14.0.4",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-prettier": "^4.2.1",
"mongoose": "^8.2.4",
"npx": "^10.2.2",
"postcss": "^8.4.16",
"prettier": "^2.8.4",
Expand Down
7 changes: 5 additions & 2 deletions packages/nextjs/pages/api/impact/index.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { CodeMetricsByProject, OSOResponse, OSOResponseProps, OnchainMetricsByProject } from "~~/app/types/OSO";
import { DataSet, ImpactVectors } from "~~/app/types/data";
import { getVectors } from "~~/utils/impactCalculator/data";
import dbConnect from "~~/services/db/dbConnect";
import ImpactVector from "~~/services/db/models/ImpactVector";

interface VectorWeight {
vector: keyof ImpactVectors;
weight: number;
}

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
dbConnect();

if (req.method !== "GET") {
return res.status(405).json({ message: "Method not allowed." });
}
Expand Down Expand Up @@ -162,7 +165,7 @@ const scoreProjectsByVectorWeight = async ({
allProjects: (CodeMetricsByProject & OnchainMetricsByProject)[];
vectorWeights: VectorWeight[];
}) => {
const allVectors = await getVectors();
const allVectors = await ImpactVector.find();

// Find the largest value for each vector and find multiple to make it 100
const normalizers: { [key in keyof ImpactVectors]: number } = {} as { [key in keyof ImpactVectors]: number };
Expand Down
10 changes: 6 additions & 4 deletions packages/nextjs/pages/api/lists/index.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { getVectorLists, insertVectorList } from "~~/utils/impactCalculator/data";
import dbConnect from "~~/services/db/dbConnect";
import VectorList from "~~/services/db/models/VectorList";

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
await dbConnect();
if (req.method === "POST") {
try {
await insertVectorList(req.body);
return res.status(201).json(req.body);
const newVectorList = await new VectorList(req.body).save();
return res.status(201).json(newVectorList);
} catch (err) {
console.log("Error inserting a vector list into db:", err);
res.status(500).json({ message: "Internal Server Error" });
}
}
if (req.method === "GET") {
try {
const vectorLists = await getVectorLists();
const vectorLists = await VectorList.find();
return res.status(200).json(vectorLists);
} catch (err) {
console.log("Error retrieving vector lists from db:", err);
Expand Down
6 changes: 4 additions & 2 deletions packages/nextjs/pages/api/vectors.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { Vector } from "~~/app/types/data";
import { getVectors } from "~~/utils/impactCalculator/data";
import dbConnect from "~~/services/db/dbConnect";
import ImpactVector from "~~/services/db/models/ImpactVector";

type ResponseData = Vector[] | { message: string };

export default async function handler(req: NextApiRequest, res: NextApiResponse<ResponseData>) {
await dbConnect();
if (req.method !== "GET") {
return res.status(405).json({ message: "Method not allowed." });
}

try {
const vectors = await getVectors();
const vectors = await ImpactVector.find();
res.status(200).json(vectors);
} catch (error) {
console.error(error);
Expand Down
43 changes: 43 additions & 0 deletions packages/nextjs/services/db/dbConnect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import mongoose from "mongoose";

declare global {
// eslint-disable-next-line
var mongoose: any; // This must be a `var` and not a `let / const`
}

// eslint-disable-next-line
const MONGODB_URI = process.env.MONGODB_URI!;

if (!MONGODB_URI) {
throw new Error("Please define the MONGODB_URI environment variable inside .env.local");
}

let cached = global.mongoose;

if (!cached) {
cached = global.mongoose = { conn: null, promise: null };
}

async function dbConnect() {
if (cached.conn) {
return cached.conn;
}
if (!cached.promise) {
const opts = {
bufferCommands: false,
};
cached.promise = mongoose.connect(MONGODB_URI, opts).then(mongoose => {
return mongoose;
});
}
try {
cached.conn = await cached.promise;
} catch (e) {
cached.promise = null;
throw e;
}

return cached.conn;
}

export default dbConnect;
27 changes: 27 additions & 0 deletions packages/nextjs/services/db/models/ImpactVector.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import mongoose from "mongoose";
import { Vector } from "~~/app/types/data";

const ImpactVectorSchema = new mongoose.Schema<Vector>({
name: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
sourceName: {
type: String,
required: true,
},
parent: {
type: String,
required: true,
},
fieldName: {
type: String,
required: true,
},
});

export default mongoose.models.ImpactVector || mongoose.model<Vector>("ImpactVector", ImpactVectorSchema);
34 changes: 34 additions & 0 deletions packages/nextjs/services/db/models/VectorList.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import mongoose from "mongoose";
import { SelectedVector, VectorList } from "~~/app/types/data";

const SelectedVectorSchema = new mongoose.Schema<SelectedVector>({
name: {
type: String,
required: true,
},
weight: {
type: Number,
required: true,
},
});

const VectorListSchema = new mongoose.Schema<VectorList>({
creator: {
type: String,
required: true,
},
title: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
vectors: {
type: [SelectedVectorSchema],
required: true,
},
});

export default mongoose.models.VectorList || mongoose.model<VectorList>("VectorList", VectorListSchema);
28 changes: 0 additions & 28 deletions packages/nextjs/services/db/mongodb.ts

This file was deleted.

15 changes: 7 additions & 8 deletions packages/nextjs/services/db/seed.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
import clientPromise from "./mongodb";
import dbConnect from "./dbConnect";
import ImpactVector from "./models/ImpactVector";
import { impactVectors } from "~~/components/impact-vector/ImpactVectors";

const seedDb = async () => {
const client = await clientPromise;
const db = client.db("impact_calculator");
const collection = db.collection("impactVectors");
const collectionSize = await collection.countDocuments();
const collectionExists = collectionSize > 0;
await dbConnect();
const numVectors = await ImpactVector.countDocuments();
const collectionExists = numVectors > 0;

if (!collectionExists) {
console.log("Seeding db with impact vector data...");
const result = await collection.insertMany(impactVectors);
console.log(`${result.insertedCount} vectors inserted.`);
const result = await ImpactVector.insertMany(impactVectors);
console.log(`${result.length} vectors inserted.`);
} else {
console.log("Vectors already exists. Skipping seeding.");
}
Expand Down
23 changes: 0 additions & 23 deletions packages/nextjs/utils/impactCalculator/data.ts

This file was deleted.

Loading

0 comments on commit aa715c0

Please sign in to comment.