How to make "defineCachedFunction" cache the return data forever? #3118
Replies: 2 comments 1 reply
-
i have try to add maxAge = Infinity, remove maxAge, remove all key it doesnt cache the data forever |
Beta Was this translation helpful? Give feedback.
-
Hi! Are you trying to cache the mongodb connexion itself? You won't be able to do so because it's not serializable (nitro uses https://github.com/unjs/unstorage under the hood to store cached data). Instead, you should use something like: // server/utils/mongodb/client.ts
let cachedMongoConnection;
export async function getMongoConnection() {
if (!cachedMongoConnection) {
cachedMongoConnection = await connect("");
}
return cachedMongoConnection;
} Then you can use it like: // server/utils/mongodb/my-entity.ts
import { getMongoConnection } from './client'
export const cachedMongoEntity = defineCachedFunction(
async (name: string) => {
const client = await getMongoConnection()
const db = client.db('my-db');
const collection = db.collection('my-entity');
return await collection.find({}).toArray(); // return serializable data
}, {
maxAge: 31536000, // one year
name: 'mongoEntity',
getKey: (name: string) => name
},
) As per your question for returning same data "forever", nitro tries to follow IETF standards in which one year is advised as a standard max value. See RFC 2616 Hope this helps! |
Beta Was this translation helpful? Give feedback.
-
i mean how to make it cached forever?
Beta Was this translation helpful? Give feedback.
All reactions