Skip to content

Commit

Permalink
fix: fixed collection update
Browse files Browse the repository at this point in the history
  • Loading branch information
mbret committed Dec 18, 2024
1 parent 6f1290d commit e47fb4d
Show file tree
Hide file tree
Showing 7 changed files with 111 additions and 52 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,15 @@ const lambda: ValidatedEventAPIGatewayProxyEvent<typeof schema> = async (
),
switchMap(([params, db]) =>
from(
findOne(db, "obokucollection", {
selector: { _id: collectionId }
})
findOne(
"obokucollection",
{
selector: { _id: collectionId }
},
{ throwOnNotFound: true, db }
)
).pipe(
mergeMap((collection) => {
if (!collection)
throw new Error(`Unable to find book ${collectionId}`)

return from(
refreshMetadata(collection, {
db,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,9 +119,9 @@ export const refreshMetadata = async (
}

// try to get latest collection to stay as fresh as possible
const currentCollection = await findOne(db, "obokucollection", {
const currentCollection = await findOne("obokucollection", {
selector: { _id: collection._id }
})
}, { db })

if (!currentCollection) throw new Error("Unable to find collection")

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ const lambda: ValidatedEventAPIGatewayProxyEvent<typeof schema> = async (

const db = await getNanoDbForUser(userName, jwtPrivateKey)

const book = await findOne(db, "book", { selector: { _id: bookId } })
const book = await findOne("book", { selector: { _id: bookId } }, { db })

if (!book) throw new Error(`Unable to find book ${bookId}`)

Expand All @@ -85,7 +85,11 @@ const lambda: ValidatedEventAPIGatewayProxyEvent<typeof schema> = async (

const firstLinkId = (book.links || [])[0] || "-1"

const link = await findOne(db, "link", { selector: { _id: firstLinkId } })
const link = await findOne(
"link",
{ selector: { _id: firstLinkId } },
{ db }
)

if (!link) throw new Error(`Unable to find link ${firstLinkId}`)

Expand Down
40 changes: 5 additions & 35 deletions packages/api/src/libs/couch/dbHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ import { User } from "../couchDbEntities"
import { waitForRandomTime } from "../utils"
import { COUCH_DB_URL } from "../../constants"
import { generatePassword } from "../authentication/generatePassword"
import { findOne } from "./findOne"

export { findOne }

export const createUser = async (
db: createNano.ServerScope,
Expand Down Expand Up @@ -104,39 +107,6 @@ export const insert = async <
return doc
}

export const findOne = async <
M extends DocType["rx_model"],
D extends ModelOf<M>
>(
db: createNano.DocumentScope<unknown>,
rxModel: M,
query: SafeMangoQuery<D>
) => {
const { fields, ...restQuery } = query
const fieldsWithRequiredFields = fields
if (Array.isArray(fieldsWithRequiredFields)) {
fieldsWithRequiredFields.push(`rx_model`)
}

const response = await retryFn(() =>
db.find({
...restQuery,
fields: fields as string[],
selector: { rx_model: rxModel, ...(query?.selector as any) },
limit: 1
})
)

if (response.docs.length === 0) return null

const doc = response
.docs[0] as createNano.MangoResponse<unknown>["docs"][number] & D

if (rxModel !== doc.rx_model) throw new Error(`Invalid document type`)

return doc
}

export const findAllDataSources = async (
db: createNano.DocumentScope<unknown>
) => {
Expand Down Expand Up @@ -246,7 +216,7 @@ export const getOrCreateTagFromName = (
) => {
return retryFn(async () => {
// Get all tag ids and create one if it does not exist
const existingTag = await findOne(db, "tag", { selector: { name } })
const existingTag = await findOne("tag", { selector: { name } }, { db })
if (existingTag) {
return existingTag._id
}
Expand Down Expand Up @@ -276,7 +246,7 @@ export const createTagFromName = (
silent: boolean
) => {
return retryFn(async () => {
const existingTag = await findOne(db, "tag", { selector: { name } })
const existingTag = await findOne("tag", { selector: { name } }, { db })

if (existingTag) {
if (silent) {
Expand Down
74 changes: 74 additions & 0 deletions packages/api/src/libs/couch/findOne.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import createNano from "nano"
import { SafeMangoQuery, DocType, ModelOf } from "@oboku/shared"
import { retryFn } from "./dbHelpers"

type FindOneOptionsBase = {
db: createNano.DocumentScope<unknown>
}

type FindOneOptionsWithThrow = FindOneOptionsBase & {
throwOnNotFound: true
}

type FindOneOptionsWithoutThrow = FindOneOptionsBase & {
throwOnNotFound?: false
}

type FindOneOptions = FindOneOptionsWithThrow | FindOneOptionsWithoutThrow

export function findOne<M extends DocType["rx_model"], D extends ModelOf<M>>(
rxModel: M,
query: SafeMangoQuery<D>,
options: FindOneOptionsWithThrow
): Promise<
D & {
_id: string
_rev: string
}
>

export function findOne<M extends DocType["rx_model"], D extends ModelOf<M>>(
rxModel: M,
query: SafeMangoQuery<D>,
options: FindOneOptionsWithoutThrow
): Promise<
| (D & {
_id: string
_rev: string
})
| null
>

export async function findOne<
M extends DocType["rx_model"],
D extends ModelOf<M>
>(rxModel: M, query: SafeMangoQuery<D>, options: FindOneOptions) {
const { fields, ...restQuery } = query
const fieldsWithRequiredFields = fields
if (Array.isArray(fieldsWithRequiredFields)) {
fieldsWithRequiredFields.push(`rx_model`)
}

const response = await retryFn(() =>
options.db.find({
...restQuery,
fields: fields as string[],
selector: { rx_model: rxModel, ...(query?.selector as any) },
limit: 1
})
)

if (response.docs.length === 0) {
if (options.throwOnNotFound) {
throw new Error("Document not found")
}
return null
}

const doc = response
.docs[0] as createNano.MangoResponse<unknown>["docs"][number] & D

if (rxModel !== doc.rx_model) throw new Error(`Invalid document type`)

return doc
}
12 changes: 8 additions & 4 deletions packages/api/src/libs/plugins/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,13 @@ export const createHelpers = (
refreshBookMetadata: (opts: { bookId: string }) =>
refreshBookMetadata(opts).catch(console.error),
getDataSourceData: async <Data>(): Promise<Partial<Data>> => {
const dataSource = await findOne(db, "datasource", {
selector: { _id: dataSourceId }
})
const dataSource = await findOne(
"datasource",
{
selector: { _id: dataSourceId }
},
{ db }
)
let data = {}
try {
if (dataSource?.data) {
Expand All @@ -40,7 +44,7 @@ export const createHelpers = (
findOne: <M extends DocType["rx_model"], D extends ModelOf<M>>(
model: M,
query: SafeMangoQuery<D>
) => findOne(db, model, query),
) => findOne(model, query, { db }),
find: <M extends DocType["rx_model"], D extends ModelOf<M>>(
model: M,
query: SafeMangoQuery<D>
Expand Down
12 changes: 9 additions & 3 deletions packages/api/src/libs/sync/collections/repairCollectionBooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,15 @@ export const repairCollectionBooks = async ({
ctx: Context
collectionId: string
}) => {
const collection = await findOne(ctx.db, "obokucollection", {
selector: { _id: collectionId }
})
const collection = await findOne(
"obokucollection",
{
selector: { _id: collectionId }
},
{
db: ctx.db
}
)

if (collection) {
const [booksHavingCollectionAttached, booksFromCollectionList] =
Expand Down

0 comments on commit e47fb4d

Please sign in to comment.