refactor(series): extract loadPublicSeries helper

This commit is contained in:
Jennie Robinson Faber 2026-04-27 11:39:57 +01:00
parent bd4561fea7
commit 5f93d4c2e3
6 changed files with 68 additions and 56 deletions

View file

@ -0,0 +1,47 @@
import Series from '../models/series.js'
import { connectDB } from './mongoose.js'
/**
* Load a series by ObjectId, string id, or slug for public endpoints.
* Series has three identifier fields (`_id`, `id`, `slug`); this helper
* builds the same conditional `$or` query the call sites would otherwise
* inline. No isVisible gate today (parity with existing call-site behavior).
*
* @param {Object} reqEvent - h3 event (reserved for future auth/cookie access)
* @param {String} identifier - ObjectId string, string id, or slug
* @param {Object} [options]
* @param {Boolean} [options.lean] - apply .lean() to the query
* @param {String} [options.select] - apply .select() to the query
* @param {Boolean} [options.allowMissing] - return null instead of throwing 404 on miss
* @returns {Promise<Object|null>} the series document, or null if allowMissing and not found
*/
export async function loadPublicSeries(reqEvent, identifier, options = {}) {
if (!identifier) {
throw createError({
statusCode: 400,
statusMessage: 'Series identifier is required'
})
}
await connectDB()
const { lean = false, select = null, allowMissing = false } = options
const isObjectId = /^[0-9a-fA-F]{24}$/.test(identifier)
const seriesQuery = isObjectId
? { $or: [{ _id: identifier }, { id: identifier }, { slug: identifier }] }
: { $or: [{ id: identifier }, { slug: identifier }] }
let query = Series.findOne(seriesQuery)
if (select) query = query.select(select)
if (lean) query = query.lean()
const series = await query
if (!series) {
if (allowMissing) return null
throw createError({ statusCode: 404, statusMessage: 'Series not found' })
}
return series
}