Skip to content

Commit

Permalink
deps: upgrade to prisma 5 and prepare for JSON types (#3874)
Browse files Browse the repository at this point in the history
  • Loading branch information
rschlaefli authored Sep 27, 2023
1 parent a2f17b8 commit 2608399
Show file tree
Hide file tree
Showing 17 changed files with 193 additions and 141 deletions.
2 changes: 1 addition & 1 deletion apps/auth/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
"prettier": "2.8.8",
"prettier-plugin-organize-imports": "3.2.3",
"prettier-plugin-tailwindcss": "0.4.1",
"prisma": "4.14.1",
"prisma": "5.3.1",
"tailwindcss": "3.3.3",
"typescript": "5.0.4"
},
Expand Down
2 changes: 1 addition & 1 deletion apps/backend-docker/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
"nodemon": "3.0.1",
"npm-run-all": "4.1.5",
"nyc": "15.1.0",
"prisma": "4.14.1",
"prisma": "5.3.1",
"tsup": "6.7.0",
"typescript": "5.0.4"
},
Expand Down
2 changes: 1 addition & 1 deletion apps/func-migration-v3-import/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
"npm-run-all": "4.1.5",
"prettier": "2.8.8",
"prettier-plugin-organize-imports": "3.2.3",
"prisma": "4.14.1",
"prisma": "5.3.1",
"ts-node": "10.9.1",
"tsup": "7.2.0",
"typescript": "5.1.6"
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
"Valentin Meyer <valentin.meyer@bf.uzh.ch>"
],
"devDependencies": {
"@prisma/nextjs-monorepo-workaround-plugin": "4.14.1",
"@prisma/nextjs-monorepo-workaround-plugin": "5.3.1",
"husky": "8.0.3",
"standard-version": "9.5.0",
"syncpack": "11.2.1",
Expand Down
2 changes: 1 addition & 1 deletion packages/graphql/src/schema/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -372,7 +372,7 @@ export const Query = builder.queryType({
sessionId: t.arg.string({ required: true }),
},
resolve(_, args, ctx) {
return SessionService.getLeaderboard(args, ctx)
return SessionService.getLeaderboard(args, ctx) as any
},
}),

Expand Down
15 changes: 9 additions & 6 deletions packages/graphql/src/services/courses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -295,12 +295,15 @@ export async function getCourseOverviewData(
)

const sortByScoreAndUsername = R.curry(R.sortWith)([
R.descend(R.prop('score')),
R.ascend(R.prop('username')),
R.descend(R.prop<number>('score')),
R.ascend(R.prop<string>('username')),
])

const sortedEntries = sortByScoreAndUsername(allEntries.mapped)
const sortedGroupEntries = sortByScoreAndUsername(allGroupEntries.mapped)
const sortedEntries: typeof allEntries.mapped = sortByScoreAndUsername(
allEntries.mapped
)
const sortedGroupEntries: typeof allGroupEntries.mapped =
sortByScoreAndUsername(allGroupEntries.mapped)

const filteredEntries = sortedEntries.flatMap((entry, ix) => {
if (ix < 10 || entry.participantId === ctx.user?.sub)
Expand Down Expand Up @@ -606,11 +609,11 @@ export async function getCourseData(
}
},
{
activeLBEntries: [] as typeof course.leaderboard,
activeLBEntries: [] as Partial<typeof course.leaderboard>,
activeSum: 0,
activeCount: 0,
}
)
) ?? {}

const totalCount = course?.participations.length || 0
const averageActiveScore = activeCount > 0 ? activeSum / activeCount : 0
Expand Down
4 changes: 2 additions & 2 deletions packages/graphql/src/services/learningElements.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
QuestionType,
UserRole,
} from '@klicker-uzh/prisma'
import { PrismaClientKnownRequestError } from '@klicker-uzh/prisma/dist/runtime/library'
import dayjs from 'dayjs'
import { GraphQLError } from 'graphql'
import * as R from 'ramda'
Expand Down Expand Up @@ -1092,8 +1093,7 @@ export async function deleteLearningElement(

return deletedItem
} catch (e) {
// TODO: resolve type issue by first testing for prisma error
if (e?.code === 'P2025') {
if (e instanceof PrismaClientKnownRequestError && e?.code === 'P2025') {
console.log(
'The learning element is not in draft status and cannot be deleted.'
)
Expand Down
4 changes: 2 additions & 2 deletions packages/graphql/src/services/microLearning.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
QuestionInstanceType,
QuestionType,
} from '@klicker-uzh/prisma'
import { PrismaClientKnownRequestError } from '@klicker-uzh/prisma/dist/runtime/library'
import { GraphQLError } from 'graphql'
import { pick } from 'ramda'
import { Context, ContextWithUser } from '../lib/context'
Expand Down Expand Up @@ -387,8 +388,7 @@ export async function deleteMicroSession(

return deletedItem
} catch (e) {
// TODO: resolve type issue by first testing for prisma error
if (e?.code === 'P2025') {
if (e instanceof PrismaClientKnownRequestError && e.code === 'P2025') {
console.log(
'The micro-session is already published and cannot be deleted anymore.'
)
Expand Down
28 changes: 19 additions & 9 deletions packages/graphql/src/services/notifications.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import { MicroSession, MicroSessionStatus } from '@klicker-uzh/prisma'
import {
Course,
MicroSession,
MicroSessionStatus,
PushSubscription,
} from '@klicker-uzh/prisma'
import { GraphQLError } from 'graphql'
import webpush from 'web-push'
import webpush, { WebPushError } from 'web-push'
import { Context, ContextWithUser } from '../lib/context'
import { formatDate } from '../lib/util'

Expand Down Expand Up @@ -115,7 +120,6 @@ export async function sendPushNotifications(ctx: Context) {
subscriptions: true,
},
},
instances: false,
},
})

Expand All @@ -125,7 +129,7 @@ export async function sendPushNotifications(ctx: Context) {
// 1. Investigate implementing this method as a background process to reduce the load on the main thread.
// 2. Investigate implementing this method in Azure
await Promise.all(
microSessions.map(async (microSession: MicroSession) => {
microSessions.map(async (microSession) => {
try {
await sendPushNotificationsToSubscribers(microSession, ctx)

Expand Down Expand Up @@ -155,10 +159,12 @@ export async function sendPushNotifications(ctx: Context) {
//E.g., store the language on the course entity and use it here to translate the message or
// store the language on the user subscription entity and use this language when sending to the specific user?
async function sendPushNotificationsToSubscribers(
microSession: MicroSession,
microSession: MicroSession & {
course: null | (Course & { subscriptions: PushSubscription[] })
},
ctx: Context
) {
for (let sub of microSession.course.subscriptions) {
for (let sub of microSession.course?.subscriptions ?? []) {
try {
const formattedDate = formatDate(microSession.scheduledEndAt)
await webpush.sendNotification(
Expand All @@ -170,16 +176,20 @@ async function sendPushNotificationsToSubscribers(
},
},
JSON.stringify({
message: `Microlearning ${microSession.displayName} for ${microSession.course.displayName} is available until ${formattedDate.date} at ${formattedDate.time}.`,
title: `KlickerUZH - New Microlearning available for the course ${microSession.course.name}`,
message: `Microlearning ${microSession.displayName} for ${
microSession.course?.displayName ?? ''
} is available until ${formattedDate.date} at ${formattedDate.time}.`,
title: `KlickerUZH - New Microlearning available for the course ${
microSession.course?.name ?? ''
}`,
})
)
} catch (error) {
console.error(
'An error occured while trying to send the push notification: ',
error
)
if (error.statusCode === 410) {
if (error instanceof WebPushError && error.statusCode === 410) {
try {
// subscription has expired or is no longer valid
// remove it from the database
Expand Down
40 changes: 31 additions & 9 deletions packages/graphql/src/services/sessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import {
AccessMode,
ConfusionTimestep,
Question,
QuestionInstance,
QuestionInstanceType,
QuestionType,
SessionBlockStatus,
Expand All @@ -13,6 +12,7 @@ import * as R from 'ramda'
import { ascend, dissoc, mapObjIndexed, pick, prop, sortWith } from 'ramda'
import { Context, ContextWithUser } from '../lib/context'
// TODO: rework scheduling for serverless
import { PrismaClientKnownRequestError } from '@klicker-uzh/prisma/dist/runtime/library'
import { GraphQLError } from 'graphql'
import { max, mean, median, min, quantileSeq, std } from 'mathjs'
import schedule from 'node-schedule'
Expand Down Expand Up @@ -765,12 +765,19 @@ export async function activateSessionBlock(
return updatedSession
}

interface GetCachedBlockResultsArgs {
ctx: Context
sessionId: string
sessionBlockId: number
activeInstanceIds: number[]
}

async function getCachedBlockResults({
ctx,
sessionId,
sessionBlockId,
activeInstanceIds,
}) {
}: GetCachedBlockResultsArgs) {
const redisMulti = ctx.redisExec.multi()
redisMulti.hgetall(`s:${sessionId}:lb`)
redisMulti.hgetall(`s:${sessionId}:b:${sessionBlockId}:lb`)
Expand All @@ -782,12 +789,19 @@ async function getCachedBlockResults({
return await redisMulti.exec()
}

interface UnlinkCachedBlockResultsArgs {
ctx: Context
sessionId: string
sessionBlockId: number
activeInstanceIds: number[]
}

async function unlinkCachedBlockResults({
ctx,
sessionId,
sessionBlockId,
activeInstanceIds,
}) {
}: UnlinkCachedBlockResultsArgs) {
// unlink everything regarding the block in redis
const unlinkMulti = ctx.redisExec.pipeline()
unlinkMulti.unlink(`s:${sessionId}:b:${sessionBlockId}:lb`)
Expand All @@ -800,7 +814,15 @@ async function unlinkCachedBlockResults({
return unlinkMulti.exec()
}

async function processCachedData({ cachedResults, activeBlock }) {
interface ProcessCachedDataArgs {
cachedResults: any[]
activeBlock: any
}

async function processCachedData({
cachedResults,
activeBlock,
}: ProcessCachedDataArgs) {
const mappedResults: any[] = cachedResults.map(([_, result]) => result)

const sessionLeaderboard: Record<string, string> = mappedResults[0]
Expand Down Expand Up @@ -1235,11 +1257,12 @@ export async function getLeaderboard(
})

const sortByScoreAndUsername = R.curry(R.sortWith)([
R.descend(R.prop('score')),
R.ascend(R.prop('username')),
R.descend(R.prop<number>('score')),
R.ascend(R.prop<string>('username')),
])

const sortedEntries = sortByScoreAndUsername(preparedEntries)
const sortedEntries: typeof preparedEntries =
sortByScoreAndUsername(preparedEntries)

const filteredEntries = sortedEntries.flatMap((entry, ix) => {
return { ...entry, rank: ix + 1 }
Expand Down Expand Up @@ -1923,8 +1946,7 @@ export async function deleteSession(

return deletedItem
} catch (e) {
// TODO: resolve type issue by first testing for prisma error
if (e?.code === 'P2025') {
if (e instanceof PrismaClientKnownRequestError && e.code === 'P2025') {
console.log(
'The learning element is not in draft status and cannot be deleted.'
)
Expand Down
6 changes: 4 additions & 2 deletions packages/prisma/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"dist"
],
"dependencies": {
"@prisma/client": "4.14.1"
"@prisma/client": "5.3.1"
},
"devDependencies": {
"@pothos/plugin-prisma": "3.56.0",
Expand All @@ -23,10 +23,12 @@
"dotenv": "16.0.3",
"dotenv-cli": "7.2.1",
"eslint": "8.45.0",
"fs-extra": "11.1.1",
"npm-run-all": "4.1.5",
"prettier": "2.8.8",
"prettier-plugin-organize-imports": "3.2.3",
"prisma": "4.14.1",
"prisma": "5.3.1",
"prisma-json-types-generator": "3.0.1",
"ramda": "0.29.0",
"size-limit": "8.2.4",
"ts-node": "10.9.1",
Expand Down
45 changes: 4 additions & 41 deletions packages/prisma/src/copy.js
Original file line number Diff line number Diff line change
@@ -1,44 +1,7 @@
const fs = require('fs')
const fs = require('fs-extra')
const path = require('path')

fs.mkdirSync(path.resolve(__dirname, '../dist/runtime'), { recursive: true })
fs.copyFileSync(
path.resolve(__dirname, './client/index.d.ts'),
path.resolve(__dirname, '../dist/index.d.ts')
)
fs.copyFileSync(
path.resolve(__dirname, './prisma/schema.prisma'),
path.resolve(__dirname, '../dist/schema.prisma')
)
fs.copyFileSync(
path.resolve(__dirname, './client/runtime/index-browser.d.ts'),
path.resolve(__dirname, '../dist/runtime/index-browser.d.ts')
)
fs.copyFileSync(
path.resolve(__dirname, './client/runtime/index.d.ts'),
path.resolve(__dirname, '../dist/runtime/index.d.ts')
)
fs.copyFileSync(
path.resolve(
__dirname,
'./client/libquery_engine-linux-musl-openssl-3.0.x.so.node'
),
path.resolve(
__dirname,
'../dist/libquery_engine-linux-musl-openssl-3.0.x.so.node'
)
)
fs.copyFileSync(
path.resolve(
__dirname,
'./client/libquery_engine-debian-openssl-1.1.x.so.node'
),
path.resolve(
__dirname,
'../dist/libquery_engine-debian-openssl-1.1.x.so.node'
)
)
fs.copyFileSync(
path.resolve(__dirname, './client/pothos.d.ts'),
path.resolve(__dirname, '../dist/pothos.d.ts')
fs.copySync(
path.resolve(__dirname, './client'),
path.resolve(__dirname, '../dist/')
)
1 change: 0 additions & 1 deletion packages/prisma/src/index.ts

This file was deleted.

12 changes: 9 additions & 3 deletions packages/prisma/src/prisma/schema.prisma
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
generator client {
provider = "prisma-client-js"
previewFeatures = ["fullTextSearch", "fullTextIndex", "postgresqlExtensions", "fieldReference", "extendedWhereUnique"]
previewFeatures = ["fullTextSearch", "fullTextIndex", "postgresqlExtensions"]
output = "../client"
binaryTargets = ["native", "debian-openssl-1.1.x", "linux-musl-openssl-3.0.x"]
}
Expand All @@ -11,6 +11,10 @@ generator pothos {
output = "../client/pothos.d.ts"
}

generator json {
provider = "prisma-json-types-generator"
}

datasource db {
provider = "postgres"
url = env("DATABASE_URL")
Expand Down Expand Up @@ -526,8 +530,10 @@ model MicroSession {
instances QuestionInstance[]
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade, onUpdate: Cascade)
ownerId String @db.Uuid
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade, onUpdate: Cascade)
ownerId String @db.Uuid
// TODO: why is course optional?
course Course? @relation(fields: [courseId], references: [id], onDelete: SetNull, onUpdate: Cascade)
courseId String? @db.Uuid
Expand Down
5 changes: 5 additions & 0 deletions packages/prisma/src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
declare global {
namespace PrismaJson {
// Insert your types here!
}
}
Loading

0 comments on commit 2608399

Please sign in to comment.