Skip to content

Instantly share code, notes, and snippets.

@djyde
Last active February 22, 2021 14:10
Show Gist options
  • Save djyde/3a233626ad137a648fbfae36b2406f52 to your computer and use it in GitHub Desktop.
Save djyde/3a233626ad137a648fbfae36b2406f52 to your computer and use it in GitHub Desktop.
Singleton helper for next.js

Synchronous

const prisma = singletonSync('prisma', () => {
  return new PrismaClient()
})

Asynchronous

const apolloServer = await singleton("apolloServer", async () => {
  const schema = await buildSchema({
    resolvers: [...],
  });

  return new ApolloServer({
    schema,
  });
});
export const singleton = async <T>(id: string, fn: () => Promise<T>) => {
if (process.env.NODE_ENV === "production") {
return await fn()
} else {
if (!global[id]) {
global[id] = await fn()
}
return global[id] as T;
}
};
export const singletonSync = <T>(id: string, fn: () => T) => {
if (process.env.NODE_ENV === "production") {
return fn();
} else {
if (!global[id]) {
global[id] = fn();
}
return global[id] as T;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment