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

update Knex dependency #443

Merged
merged 7 commits into from
Feb 12, 2024
Merged
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
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -142,15 +142,15 @@
"immutable": "^4.0.0-rc.12",
"jest-diff": "^25.5.0",
"keycloak-connect": "^8.0.0",
"knex": "0.19.5",
"knex": "2.5.1",
"lodash": "^4.17.21",
"mime-types": "^2.1.22",
"module-alias": "^2.2.2",
"moment": "^2.24.0",
"multiparty": "^4.2.1",
"nodemailer": "^6.6.1",
"openid-client": "^3.15.9",
"pg": "8.7.x",
"pg": "8.11.x",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"sha.js": "^2.4.11",
Expand Down
12 changes: 11 additions & 1 deletion src/back-end/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import findUp from "find-up";
import { existsSync, mkdirSync } from "fs";
import { dirname, join, resolve } from "path";
import { parseBooleanEnvironmentVariable } from "shared/config";
import { ConnectionConfig } from "knex";

// HARDCODED CONFIG
// Offset for total opportunity metrics displayed on landing page
Expand Down Expand Up @@ -86,6 +85,17 @@ export const SWAGGER_ENABLE = get("SWAGGER_ENABLE", "") === "true";

export const SWAGGER_UI_PATH = get("SWAGGER_UI_PATH", "/docs/api");

interface ConnectionConfig {
host: string;
user: string;
password: string;
database: string;
domain?: string;
instanceName?: string;
debug?: boolean;
requestTimeout?: number;
}

export function getPGConfig(): string | ConnectionConfig {
let connectionConfig: string | ConnectionConfig = "";
if (
Expand Down
22 changes: 11 additions & 11 deletions src/back-end/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ import {
} from "back-end/lib/types";
import { Application } from "express";
import { Server } from "http";
import Knex from "knex";
import { Knex, knex } from "knex";
import { concat, flatten, flow, map } from "lodash/fp";
import { flipCurried } from "shared/lib";
import {
Expand Down Expand Up @@ -105,19 +105,19 @@ if (configErrors.length || !PG_CONFIG) {

const logger = makeDomainLogger(consoleAdapter, "back-end");

const config: Knex.Config = {
client: "pg",
connection: PG_CONFIG,
migrations: {
tableName: DB_MIGRATIONS_TABLE_NAME
},
debug: KNEX_DEBUG
};

export const connectToDatabase: () => Connection = (() => {
let _connection: Connection | null = null;
return function (): Connection {
_connection =
_connection ||
Knex({
client: "pg",
connection: PG_CONFIG,
migrations: {
tableName: DB_MIGRATIONS_TABLE_NAME
},
debug: KNEX_DEBUG
});
_connection = _connection || knex(config);
return _connection;
};
})();
Expand Down
13 changes: 7 additions & 6 deletions src/back-end/lib/db/content.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ export const readManyContent = tryDb<[], ContentSlim[]>(async (connection) => {
export const readOneContentById = tryDb<[Id, Session], Content | null>(
async (connection, id, session) => {
const result = await generateContentQuery(connection, session)
.where({ "content.id": id })
.where("content.id", id)
.first();
return valid(result ? await rawContentToContent(connection, result) : null);
}
Expand All @@ -119,7 +119,7 @@ export const readOneContentById = tryDb<[Id, Session], Content | null>(
export const readOneContentBySlug = tryDb<[string, Session], Content | null>(
async (connection, slug, session) => {
const result = await generateContentQuery(connection, session)
.where({ "content.slug": slug })
.where("content.slug", slug)
.first();
return valid(result ? await rawContentToContent(connection, result) : null);
}
Expand Down Expand Up @@ -188,7 +188,7 @@ export const updateContent = tryDb<
// Update slug on root record
const [rootContentRecord] = await connection<RootContentRecord>("content")
.transacting(trx)
.where({ id })
.where("id", id)
.update(
{
slug
Expand Down Expand Up @@ -232,9 +232,10 @@ export const updateContent = tryDb<

export const deleteContent = tryDb<[Id, Session], Content>(
async (connection, id, session) => {
const [result] = await generateContentQuery(connection, session).where({
"content.id": id
});
const [result] = await generateContentQuery(connection, session).where(
"content.id",
id
);

if (!result) {
throw new Error("unable to retrieve content for deletion");
Expand Down
2 changes: 1 addition & 1 deletion src/back-end/lib/db/counter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { Counter } from "shared/lib/resources/counter";
export const incrementCounters = tryDb<[string[]], Record<string, number>>(
async (connection, names) => {
// Update existing counters
const existingCounters = await connection<Counter>("viewCounters")
const existingCounters: string[] = await connection<Counter>("viewCounters")
.whereIn("name", names)
.increment("count")
.update({}, "name");
Expand Down
2 changes: 1 addition & 1 deletion src/back-end/lib/db/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { makeDomainLogger } from "back-end/lib/logger";
import { console as consoleAdapter } from "back-end/lib/logger/adapters";
import Knex from "knex";
import { Knex } from "knex";
import { invalid, Validation } from "shared/lib/validation";

const logger = makeDomainLogger(consoleAdapter, "back-end");
Expand Down
7 changes: 5 additions & 2 deletions src/back-end/lib/db/metrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,18 @@ export const readOpportunityMetrics = tryDb<[], OpportunityMetrics>(
});

totals.totalCount += cwuResult?.length || 0;
totals.totalAwarded += cwuResult.reduce((acc, val) => acc + val.reward, 0);
totals.totalAwarded += cwuResult.reduce(
(acc: number, val: Record<string, number>) => acc + val.reward,
0
);

const swuResult = await swuQuery(connection).where({
"statuses.status": SWUOpportunityStatus.Awarded
});

totals.totalCount += swuResult?.length || 0;
totals.totalAwarded += swuResult.reduce(
(acc, val) => acc + val.totalMaxBudget,
(acc: number, val: Record<string, number>) => acc + val.totalMaxBudget,
0
);

Expand Down
29 changes: 18 additions & 11 deletions src/back-end/lib/db/opportunity/code-with-us.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
import { RawCWUOpportunitySubscriber } from "back-end/lib/db/subscribers/code-with-us";
import { readOneUser, readOneUserSlim } from "back-end/lib/db/user";
import * as cwuOpportunityNotifications from "back-end/lib/mailer/notifications/opportunity/code-with-us";
import { QueryBuilder } from "knex";
import { Knex } from "knex";
import { valid } from "shared/lib/http";
import { getCWUOpportunityViewsCounterName } from "shared/lib/resources/counter";
import { FileRecord } from "shared/lib/resources/file";
Expand Down Expand Up @@ -243,7 +243,7 @@ async function rawCWUOpportunityHistoryRecordToCWUOpportunityHistoryRecord(
function processForRole<T extends RawCWUOpportunity | RawCWUOpportunitySlim>(
result: T,
session: Session
) {
): T {
// Remove createdBy/updatedBy for non-admin or non-author
if (
!session ||
Expand Down Expand Up @@ -305,7 +305,7 @@ export function generateCWUOpportunityQuery(
connection: Connection,
full = false
) {
const query: QueryBuilder = connection<RawCWUOpportunity>(
const query: Knex.QueryBuilder = connection<RawCWUOpportunity>(
"cwuOpportunities as opp"
)
// Join on latest CWU status
Expand Down Expand Up @@ -421,20 +421,24 @@ export const readOneCWUOpportunity = tryDb<
result = processForRole(result, session);
result.attachments = (
await connection<{ file: Id }>("cwuOpportunityAttachments")
.where({ opportunityVersion: result.versionId })
.where("opportunityVersion", result.versionId)
.select("file")
).map((row) => row.file);
result.addenda = (
await connection<{ id: Id }>("cwuOpportunityAddenda")
.where({ opportunity: id })
.where("opportunity", id)
.select("id")
).map((row) => row.id);

// Get published date if applicable
const conditions = {
opportunity: result.id,
status: CWUOpportunityStatus.Published
};
const publishedDate = await connection<{ createdAt: Date }>(
"cwuOpportunityStatuses"
)
.where({ opportunity: result.id, status: CWUOpportunityStatus.Published })
.where(conditions)
.select("createdAt")
.orderBy("createdAt", "asc")
.first();
Expand Down Expand Up @@ -481,7 +485,7 @@ export const readOneCWUOpportunity = tryDb<
const rawStatusArray = await connection<RawCWUOpportunityHistoryRecord>(
"cwuOpportunityStatuses"
)
.where({ opportunity: result.id })
.where("opportunity", result.id)
.orderBy("createdAt", "desc");

if (!rawStatusArray) {
Expand All @@ -494,7 +498,7 @@ export const readOneCWUOpportunity = tryDb<
async (raw) =>
(raw.attachments = (
await connection<{ file: Id }>("cwuOpportunityNoteAttachments")
.where({ event: raw.id })
.where("event", raw.id)
.select("file")
).map((row) => row.file))
)
Expand All @@ -513,10 +517,13 @@ export const readOneCWUOpportunity = tryDb<

if (publicOpportunityStatuses.includes(result.status)) {
// Retrieve opportunity views
const conditions = {
name: getCWUOpportunityViewsCounterName(result.id)
};
const numViews =
(
await connection<{ count: number }>("viewCounters")
.where({ name: getCWUOpportunityViewsCounterName(result.id) })
.where(conditions)
.first()
)?.count || 0;

Expand Down Expand Up @@ -624,7 +631,7 @@ export const readManyCWUOpportunities = tryDb<[Session], CWUOpportunitySlim[]>(
const results = await Promise.all(
(
await query
).map(async (result) => {
).map(async (result: RawCWUOpportunity | RawCWUOpportunitySlim) => {
if (session) {
result.subscribed = await isSubscribed(
connection,
Expand Down Expand Up @@ -964,7 +971,7 @@ export const readOneCWUOpportunityAuthor = tryDb<[Id], User | null>(
const authorId =
(
await connection<{ createdBy: Id }>("cwuOpportunities as opportunities")
.where({ id })
.where("id", id)
.select<{ createdBy: Id }>("createdBy")
.first()
)?.createdBy || null;
Expand Down
Loading