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

refactor: improve typings and simplify logic #1669

Merged
merged 1 commit into from
Nov 10, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
18 changes: 9 additions & 9 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,23 +42,23 @@
"test:unit": "nuxi prepare test/fixtures/basic && nuxi prepare test/fixtures/document-driven && vitest run"
},
"dependencies": {
"@nuxt/kit": "^3.0.0-rc.12",
"@nuxt/kit": "^3.0.0-rc.13",
"consola": "^2.15.3",
"defu": "^6.1.0",
"destr": "^1.2.0",
"detab": "^3.0.1",
"html-tags": "^3.2.0",
"json5": "^2.2.1",
"knitwork": "^0.1.2",
"listhen": "^0.3.4",
"listhen": "^0.3.5",
"mdast-util-to-hast": "^12.2.4",
"mdurl": "^1.0.1",
"ohash": "^0.1.5",
"pathe": "^0.3.9",
"property-information": "^6.1.1",
"rehype-external-links": "^2.0.1",
"rehype-raw": "^6.1.1",
"rehype-slug": "^5.0.1",
"rehype-slug": "^5.1.0",
"rehype-sort-attribute-values": "^4.0.0",
"rehype-sort-attributes": "^4.0.0",
"remark-emoji": "^3.0.2",
Expand All @@ -77,26 +77,26 @@
"unist-util-position": "^4.0.3",
"unist-util-visit": "^4.1.1",
"unstorage": "^0.6.0",
"ws": "^8.10.0"
"ws": "^8.11.0"
},
"devDependencies": {
"@nuxt/module-builder": "^0.2.0",
"@nuxt/schema": "^3.0.0-rc.12",
"@nuxt/test-utils": "^3.0.0-rc.12",
"@nuxt/schema": "^3.0.0-rc.13",
"@nuxt/test-utils": "^3.0.0-rc.13",
"@nuxthq/admin": "npm:@nuxthq/admin-edge@latest",
"@nuxtjs/eslint-config-typescript": "latest",
"@types/ws": "^8.5.3",
"c8": "^7.12.0",
"csvtojson": "^2.0.10",
"eslint": "^8.26.0",
"eslint": "^8.27.0",
"globby": "^13.1.2",
"husky": "^8.0.1",
"husky": "^8.0.2",
"jiti": "^1.16.0",
"lint-staged": "^13.0.3",
"nuxt": "npm:nuxt3@latest",
"rehype-figure": "^1.0.1",
"remark-oembed": "^1.2.2",
"vitest": "^0.24.3",
"vitest": "^0.25.1",
"vue-docgen-web-types": "^0.1.8"
}
}
14 changes: 10 additions & 4 deletions src/runtime/query/match/pipeline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,20 @@ export function createPipelineFetcher<T> (getContentsList: () => Promise<T[]>) {
// Remove unwanted fields
(data, params) => apply(withoutKeys(params.without))(data),
// Select only wanted fields
(data, params) => apply(withKeys(params.only))(data),
// Evaluate result
(data, params) => params.first ? data[0] : data
(data, params) => apply(withKeys(params.only))(data)
]

return async (query: QueryBuilder<T>): Promise<T | T[]> => {
const data = await getContentsList()
const params = query.params()

return pipelines.reduce(($data: Array<T>, pipe: any) => pipe($data, query.params()) || $data, data)
const filteredData = pipelines.reduce(($data: Array<T>, pipe: QueryPipe) => pipe($data, params) || $data, data)

// return first item if query is for single item
if (params.first) {
return filteredData[0]
}

return filteredData
}
}
34 changes: 20 additions & 14 deletions src/runtime/server/api/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,33 +5,39 @@ import { getContentQuery } from '../../utils/query'

export default defineEventHandler(async (event) => {
const query = getContentQuery(event)
const contents = await serverQueryContent(event, query).find()

if (query.first) {
const path = contents?._path || query.where.find(w => w._path)?._path
const content = await serverQueryContent(event, query).findOne()

// Try to find `_dir` file before throwing 404
const path = content?._path || query.where?.find(w => w._path)?._path as string
if (path) {
const _dir = await serverQueryContent(event).where({ _path: join(path, '_dir') }).without('_').findOne()
if (!Array.isArray(_dir)) {
return {
_path: path,
...contents,
...(content || {}),
_dir
}
}
}
}

// If no documents matchs and using findOne()
if (query.first && Array.isArray(contents) && contents.length === 0) {
throw createError({
statusMessage: 'Document not found!',
statusCode: 404,
data: {
description: 'Could not find document for the given query.',
query
}
})
// If no documents matchs and using findOne()
if (!content) {
throw createError({
statusMessage: 'Document not found!',
statusCode: 404,
data: {
description: 'Could not find document for the given query.',
query
}
})
}

return content
}

const contents = await serverQueryContent(event, query).find()

return contents
})
6 changes: 3 additions & 3 deletions src/runtime/server/content-index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import type { CompatibilityEvent } from 'h3'
import type { H3Event } from 'h3'
import type { ParsedContent, QueryBuilder } from '../types'
import { isPreview } from './preview'
import { cacheStorage, getContent, getContentsList, serverQueryContent } from './storage'

export async function getContentIndex (event: CompatibilityEvent) {
export async function getContentIndex (event: H3Event) {
let contentIndex = await cacheStorage.getItem('content-index.json') as Record<string, string>
if (!contentIndex) {
// Fetch all content
Expand All @@ -24,7 +24,7 @@ export async function getContentIndex (event: CompatibilityEvent) {
return contentIndex
}

export async function getIndexedContentsList<T = ParsedContent> (event: CompatibilityEvent, query: QueryBuilder<T>): Promise<T[]> {
export async function getIndexedContentsList<T = ParsedContent> (event: H3Event, query: QueryBuilder<T>): Promise<T[]> {
const params = query.params()
const path = params?.where?.find(wh => wh._path)?._path

Expand Down
6 changes: 3 additions & 3 deletions src/runtime/server/preview.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import type { CompatibilityEvent } from 'h3'
import type { H3Event } from 'h3'
import { getQuery, getCookie } from 'h3'

export const isPreview = (event: CompatibilityEvent) => {
export const isPreview = (event: H3Event) => {
const previewToken = getQuery(event).previewToken || getCookie(event, 'previewToken')
return !!previewToken
}

export const getPreview = (event: CompatibilityEvent) => {
export const getPreview = (event: H3Event) => {
const key = getQuery(event).previewToken as string || getCookie(event, 'previewToken')

return { key }
Expand Down
18 changes: 9 additions & 9 deletions src/runtime/server/storage.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { prefixStorage } from 'unstorage'
import { joinURL, withLeadingSlash, withoutTrailingSlash } from 'ufo'
import { hash as ohash } from 'ohash'
import type { CompatibilityEvent } from 'h3'
import type { H3Event } from 'h3'
// eslint-disable-next-line import/no-named-as-default
import defu from 'defu'
import type { QueryBuilderParams, ParsedContent, QueryBuilder, ContentTransformer } from '../types'
Expand Down Expand Up @@ -67,7 +67,7 @@ const contentIgnorePredicate = (key: string) => {
return true
}

export const getContentsIds = async (event: CompatibilityEvent, prefix?: string) => {
export const getContentsIds = async (event: H3Event, prefix?: string) => {
let keys = []

if (isProduction) {
Expand Down Expand Up @@ -103,14 +103,14 @@ export const getContentsIds = async (event: CompatibilityEvent, prefix?: string)
return keys.filter(contentIgnorePredicate)
}

export const getContentsList = async (event: CompatibilityEvent, prefix?: string) => {
export const getContentsList = async (event: H3Event, prefix?: string) => {
const keys = await getContentsIds(event, prefix)
const contents = await Promise.all(keys.map(key => getContent(event, key)))

return contents
}

export const getContent = async (event: CompatibilityEvent, id: string): Promise<ParsedContent> => {
export const getContent = async (event: H3Event, id: string): Promise<ParsedContent> => {
const contentId = id
// Handle ignored id
if (!contentIgnorePredicate(id)) {
Expand Down Expand Up @@ -187,7 +187,7 @@ export async function parseContent (id: string, content: string, opts: ParseCont
return result
}

export const createServerQueryFetch = <T = ParsedContent>(event: CompatibilityEvent, path?: string) => (query: QueryBuilder<T>) => {
export const createServerQueryFetch = <T = ParsedContent>(event: H3Event, path?: string) => (query: QueryBuilder<T>) => {
if (path) {
if (query.params().first) {
query.where({ _path: withoutTrailingSlash(path) })
Expand All @@ -207,10 +207,10 @@ export const createServerQueryFetch = <T = ParsedContent>(event: CompatibilityEv
/**
* Query contents
*/
export function serverQueryContent<T = ParsedContent>(event: CompatibilityEvent): QueryBuilder<T>;
export function serverQueryContent<T = ParsedContent>(event: CompatibilityEvent, params?: QueryBuilderParams): QueryBuilder<T>;
export function serverQueryContent<T = ParsedContent>(event: CompatibilityEvent, path?: string, ...pathParts: string[]): QueryBuilder<T>;
export function serverQueryContent<T = ParsedContent> (event: CompatibilityEvent, path?: string | QueryBuilderParams, ...pathParts: string[]) {
export function serverQueryContent<T = ParsedContent>(event: H3Event): QueryBuilder<T>;
export function serverQueryContent<T = ParsedContent>(event: H3Event, params?: QueryBuilderParams): QueryBuilder<T>;
export function serverQueryContent<T = ParsedContent>(event: H3Event, path?: string, ...pathParts: string[]): QueryBuilder<T>;
export function serverQueryContent<T = ParsedContent> (event: H3Event, path?: string | QueryBuilderParams, ...pathParts: string[]) {
if (typeof path === 'string') {
path = withLeadingSlash(joinURL(path, ...pathParts))
return createQuery<T>(createServerQueryFetch(event, path))
Expand Down
15 changes: 8 additions & 7 deletions src/runtime/utils/query.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getQuery, CompatibilityEvent, createError } from 'h3'
import { getQuery, H3Event, createError } from 'h3'
import { QueryBuilderParams } from '../types'
import { jsonParse } from './json'

Expand All @@ -11,7 +11,7 @@ const parseQueryParams = (body: string) => {
}

const memory = {}
export const getContentQuery = (event: CompatibilityEvent): QueryBuilderParams => {
export const getContentQuery = (event: H3Event): QueryBuilderParams => {
const qid = event.context.params.qid?.replace(/.json$/, '')
const query: any = getQuery(event) || {}

Expand Down Expand Up @@ -49,11 +49,6 @@ export const getContentQuery = (event: CompatibilityEvent): QueryBuilderParams =
delete query[key]
}
}
if (Object.keys(where).length > 0) {
query.where = [where]
} else {
delete query.where
}

// ?sortyBy=size:1
if (query.sort) {
Expand All @@ -70,5 +65,11 @@ export const getContentQuery = (event: CompatibilityEvent): QueryBuilderParams =
query.where[key] = query[key]
}

if (Object.keys(where).length > 0) {
query.where = [where]
} else {
delete query.where
}

return query
}