Skip to content

Commit

Permalink
feat: auto imports for useConfig and useStorage
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Apr 6, 2022
1 parent 0661fa9 commit 5b2c950
Show file tree
Hide file tree
Showing 10 changed files with 31 additions and 23 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,10 +127,10 @@ import { storage } from '#nitro'
**Example:** Simple operations
```js
import { storage } from '#nitro'
import { useStorage } from '#nitro'
await storage.setItem('test:foo', { hello: world })
await storage.getItem('test:foo')
await useStorage().setItem('test:foo', { hello: world })
await useStorage().getItem('test:foo')
```
Expand Down
4 changes: 3 additions & 1 deletion src/imports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ export const nitroImports: Preset[] = [
from: '#nitro',
imports: [
'defineCachedFunction',
'defineCachedEventHandler'
'defineCachedEventHandler',
'useConfig',
'useStorage'
]
},
{
Expand Down
4 changes: 3 additions & 1 deletion src/rollup/plugins/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@ import { assets } from '#nitro/virtual/server-assets'
${driverImports.map(i => `import ${serializeImportName(i)} from '${i}'`).join('\n')}
export const storage = createStorage({})
const storage = createStorage({})
export const useStorage = () => storage
storage.mount('/assets', assets)
Expand Down
4 changes: 3 additions & 1 deletion src/runtime/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ import { createFetch, Headers } from 'ohmyfetch'
import destr from 'destr'
import { createRouter as createMatcher } from 'radix3'
import { createCall, createFetch as createLocalFetch } from 'unenv/runtime/fetch/index'
import { config } from './config'
import { useConfig } from './config'
import { timingMiddleware } from './timing'
import { cachedEventHandler } from './cache'
import handleError from '#nitro/error'
import { handlers } from '#nitro/virtual/server-handlers'

const config = useConfig()

export const app = createApp({
debug: destr(process.env.DEBUG),
onError: handleError
Expand Down
18 changes: 9 additions & 9 deletions src/runtime/cache.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { hash } from 'ohash'
import { H3Response, toEventHandler, handleCacheHeaders } from 'h3'
import type { CompatibilityEventHandler, CompatibilityEvent } from 'h3'
import { storage } from '#nitro'
import { useStorage } from '#nitro'

export interface CacheEntry<T=any> {
value?: T
Expand Down Expand Up @@ -40,7 +40,7 @@ export function defineCachedFunction <T=any> (fn: ((...args) => T | Promise<T>),

async function get (key: string, resolver: () => T | Promise<T>): Promise<CacheEntry<T>> {
const cacheKey = [opts.base, group, name, key].filter(Boolean).join(':')
const entry: CacheEntry<T> = await storage.getItem(cacheKey) as any || {}
const entry: CacheEntry<T> = await useStorage().getItem(cacheKey) as any || {}

const ttl = (opts.magAge ?? opts.magAge ?? 0) * 1000
if (ttl) {
Expand All @@ -57,7 +57,7 @@ export function defineCachedFunction <T=any> (fn: ((...args) => T | Promise<T>),
entry.mtime = Date.now()
entry.integrity = integrity
delete pending[key]
storage.setItem(cacheKey, entry).catch(error => console.error('[nitro] [cache]', error))
useStorage().setItem(cacheKey, entry).catch(error => console.error('[nitro] [cache]', error))
}

const _resolvePromise = expired ? _resolve() : Promise.resolve()
Expand Down Expand Up @@ -88,13 +88,13 @@ function getKey (...args: string[]) {
return args.length ? hash(args, {}) : ''
}

export function defineCachedEventHandler (handler: CompatibilityEventHandler, opts: Omit<CachifyOptions, 'getKey'> = defaultCacheOptions) {
interface ResponseCacheEntry {
body: H3Response
code: number
headers: Record<string, string | number | string[]>
}
export interface ResponseCacheEntry {
body: H3Response
code: number
headers: Record<string, string | number | string[]>
}

export function defineCachedEventHandler (handler: CompatibilityEventHandler, opts: Omit<CachifyOptions, 'getKey'> = defaultCacheOptions) {
const _opts: CachifyOptions<ResponseCacheEntry> = {
...opts,
getKey: req => req.originalUrl || req.url,
Expand Down
3 changes: 2 additions & 1 deletion src/runtime/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ for (const key in _runtimeConfig) {
}

// Named exports
export const config = deepFreeze(_runtimeConfig)
const config = deepFreeze(_runtimeConfig)
export const useConfig = () => config
export default config

// Utils
Expand Down
4 changes: 2 additions & 2 deletions src/runtime/entries/cloudflare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { getAssetFromKV, mapRequestToAsset } from '@cloudflare/kv-asset-handler'
import { withoutBase } from 'ufo'
import { localCall } from '../app'
import { requestHasBody, useRequestBody } from '../utils'
import { config } from '#nitro'
import { useConfig } from '#nitro'

addEventListener('fetch', (event: any) => {
event.respondWith(handleEvent(event))
Expand Down Expand Up @@ -53,6 +53,6 @@ function assetsCacheControl (_request) {
}

const baseURLModifier = (request: Request) => {
const url = withoutBase(request.url, config.nitro.baseURL)
const url = withoutBase(request.url, useConfig().nitro.baseURL)
return mapRequestToAsset(new Request(url, request))
}
4 changes: 2 additions & 2 deletions src/runtime/entries/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Server as HttpServer } from 'http'
import { Server as HttpsServer } from 'https'
import destr from 'destr'
import { app } from '../app'
import { config } from '#nitro'
import { useConfig } from '#nitro'

const cert = process.env.NITRO_SSL_CERT
const key = process.env.NITRO_SSL_KEY
Expand All @@ -20,7 +20,7 @@ server.listen(port, hostname, (err) => {
process.exit(1)
}
const protocol = cert && key ? 'https' : 'http'
console.log(`Listening on ${protocol}://${hostname}:${port}${config.nitro.baseURL}`)
console.log(`Listening on ${protocol}://${hostname}:${port}${useConfig().nitro.baseURL}`)
})

export default {}
4 changes: 2 additions & 2 deletions src/runtime/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export { storage } from '#nitro/virtual/storage'
export { config } from './config'
export { useStorage } from '#nitro/virtual/storage'
export { useConfig } from './config'
export { defineCachedFunction, defineCachedEventHandler } from './cache'
3 changes: 2 additions & 1 deletion src/runtime/virtual/storage.d.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
import type { Storage } from 'unstorage'
export const storage: Storage

export const useStorage = () => Storage

0 comments on commit 5b2c950

Please sign in to comment.