type-graphql#buildSchema TypeScript Examples
The following examples show how to use
type-graphql#buildSchema.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.ts From type-graphql-dataloader with MIT License | 6 votes |
export async function listen(
port: number,
resolvers: NonEmptyArray<Function>
): Promise<ListenResult> {
const app = express();
const schema = await buildSchema({
resolvers,
});
const apollo = new ApolloServer({
schema,
plugins: [
ApolloServerLoaderPlugin({
typeormGetConnection: getConnection,
}),
],
});
await apollo.start();
apollo.applyMiddleware({ app, cors: false });
const server = http.createServer(app);
await promisify(server.listen.bind(server, port))();
return {
port: (server.address() as AddressInfo).port,
close: promisify(server.close).bind(server),
};
}
Example #2
Source File: resolver.helpers.ts From Cromwell with MIT License | 6 votes |
setupResolver = async (name: string): Promise<ApolloServer> => {
await setupConnection(name);
const schema = await buildSchema({
resolvers: [...(await getResolvers())] as any,
validate: false,
authChecker: () => true,
});
const apolloServer = new ApolloServer({
schema,
context: (): TGraphQLContext => {
return {
user: {
id: 1,
email: '[email protected]',
role: 'administrator',
}
}
}
});
return apolloServer;
}
Example #3
Source File: testSchemaTypeGraphql.ts From ra-data-prisma with MIT License | 6 votes |
testSchemaTypeGraphql = async (options: CommonOptions) => {
return buildSchema({
resolvers: [
CustomUserResolver,
UserCrudResolver,
UserRelationsResolver,
UserRoleCrudResolver,
CompanyCrudResolver,
BlogPostCrudResolver,
BlogPostCommentCrudResolver,
],
validate: false,
});
}
Example #4
Source File: typegraphql-options.factory.ts From typegraphql-nestjs with MIT License | 6 votes |
async createGqlOptions(): Promise<GqlModuleOptions> {
const { globalMiddlewares } = this.rootModuleOptions;
const { resolversClasses, container, orphanedTypes } =
this.optionsPreparatorService.prepareOptions<TypeGraphQLFeatureModuleOptions>(
TYPEGRAPHQL_FEATURE_MODULE_OPTIONS,
globalMiddlewares,
);
const schema = await buildSchema({
...this.rootModuleOptions,
resolvers: resolversClasses as NonEmptyArray<ClassType>,
orphanedTypes,
container,
});
return {
...this.rootModuleOptions,
schema,
};
}
Example #5
Source File: build-federated-schema.ts From opensaas with MIT License | 6 votes |
export async function buildFederatedSchema(
options: Omit<BuildSchemaOptions, 'skipCheck'>,
referenceResolvers?: GraphQLResolverMap<any>,
) {
const schema = await buildSchema({
...options,
directives: [...specifiedDirectives, ...federationDirectives, ...(options.directives || [])],
skipCheck: true,
});
const federatedSchema = buildApolloFederationSchema({
typeDefs: gql(printSchema(schema)),
resolvers: createResolversMap(schema) as any,
});
if (referenceResolvers) {
addResolversToSchema(federatedSchema, referenceResolvers);
}
return federatedSchema;
}
Example #6
Source File: create-schema.ts From convoychat with GNU General Public License v3.0 | 6 votes |
createSchema = () => {
return buildSchema({
resolvers: [
RoomResolver,
UserResolver,
MessageResolver,
InvitationResolver,
NotificationResolver,
MessageSubscriptions,
NotificationsSubscriptions,
],
globalMiddlewares: [TypegooseMiddleware],
scalarsMap: [{ type: ObjectID, scalar: ObjectIdScalar }],
authChecker: useAuth,
});
}
Example #7
Source File: graphql.ts From hakka with MIT License | 6 votes |
getSchema = async () => {
const _schema =
schema ||
(await buildSchema({
resolvers: [
CurrentUserResolver,
AuthResolver,
TopicResolver,
CommentResolver,
NotificationResolver,
UserResolver,
],
}))
if (process.env.NODE_ENV === 'production') {
schema = _schema
}
return _schema
}
Example #8
Source File: index.ts From lireddit with MIT License | 5 votes |
main = async () => {
const conn = await createConnection({
type: "postgres",
url: process.env.DATABASE_URL,
logging: true,
// synchronize: true,
migrations: [path.join(__dirname, "./migrations/*")],
entities: [Post, User, Updoot],
});
// await conn.runMigrations();
// await Post.delete({});
const app = express();
const RedisStore = connectRedis(session);
const redis = new Redis(process.env.REDIS_URL);
app.set("trust proxy", 1);
app.use(
cors({
origin: process.env.CORS_ORIGIN,
credentials: true,
})
);
app.use(
session({
name: COOKIE_NAME,
store: new RedisStore({
client: redis,
disableTouch: true,
}),
cookie: {
maxAge: 1000 * 60 * 60 * 24 * 365 * 10, // 10 years
httpOnly: true,
sameSite: "lax", // csrf
secure: __prod__, // cookie only works in https
domain: __prod__ ? ".codeponder.com" : undefined,
},
saveUninitialized: false,
secret: process.env.SESSION_SECRET,
resave: false,
})
);
const apolloServer = new ApolloServer({
schema: await buildSchema({
resolvers: [HelloResolver, PostResolver, UserResolver],
validate: false,
}),
context: ({ req, res }) => ({
req,
res,
redis,
userLoader: createUserLoader(),
updootLoader: createUpdootLoader(),
}),
});
apolloServer.applyMiddleware({
app,
cors: false,
});
app.listen(parseInt(process.env.PORT), () => {
console.log("server started on localhost:4000");
});
}
Example #9
Source File: index.ts From Koa-GraphQL-Template with MIT License | 5 votes |
async function getSchema() {
return buildSchema({
resolvers: getResolvers()
});
}
Example #10
Source File: GraphQLSchema.ts From liferay-grow with MIT License | 5 votes |
getSchema(): Promise<IGraphQLSchema> {
return buildSchema({
authChecker: this.customAuthChecker,
resolvers: [this.resolversPath],
});
}
Example #11
Source File: application.ts From mikro-orm-graphql-example with MIT License | 5 votes |
public init = async (): Promise<void> => {
this.host = express();
if (process.env.NODE_ENV !== 'production') {
this.host.get('/graphql', expressPlayground({ endpoint: '/graphql' }));
}
this.host.use(cors());
try {
const schema: GraphQLSchema = await buildSchema({
resolvers: [BookResolver, AuthorResolver],
dateScalarMode: 'isoDate',
});
this.host.post(
'/graphql',
bodyParser.json(),
graphqlHTTP((req, res) => ({
schema,
context: { req, res, em: this.orm.em.fork() } as MyContext,
customFormatErrorFn: (error) => {
throw error;
},
})),
);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
this.host.use((error: Error, req: express.Request, res: express.Response, next: express.NextFunction): void => {
console.error('? Something went wrong', error);
res.status(400).send(error);
});
const port = process.env.PORT || 4000;
this.server = this.host.listen(port, () => {
console.log(`? http://localhost:${port}/graphql`);
});
} catch (error) {
console.error('? Could not start server', error);
}
};
Example #12
Source File: index.ts From Wern-Fullstack-Template with MIT License | 5 votes |
main = async () => {
console.log(process.env.DATABASE_URL)
/*const conn =*/ await createConnection({
type: 'postgres',
url: process.env.DATABASE_URL,
logging: true,
// do not want synchronize true in production, possiblility of losing data
synchronize: false,
entities: [UserAccount],
migrations: [path.join(__dirname, './migrations/*')],
// need this to use postgres heroku plugin
ssl: {
rejectUnauthorized: false,
},
})
// await conn.runMigrations()
const app = express()
app.set('trust proxy', 1)
app.use(
cors({
origin: process.env.CORS_ORIGIN,
credentials: true,
})
)
const apolloServer = new ApolloServer({
schema: await buildSchema({
resolvers: [UserResolver],
validate: false,
}),
context: ({ req, res }) => ({
req,
res,
}),
})
apolloServer.applyMiddleware({
app,
cors: false,
path: '/',
})
app.listen(parseInt(process.env.PORT!), () => {
console.log(`server started on localhost:${process.env.PORT!}`)
})
}
Example #13
Source File: newsletter.resolver.test.ts From Cromwell with MIT License | 5 votes |
describe('plugin-newsletter.resolver', () => {
let server: ApolloServer;
beforeAll(async () => {
const schema = await buildSchema({
resolvers: [PluginNewsletterResolver],
validate: false,
authChecker: () => true,
});
server = new ApolloServer({
schema,
context: (): TGraphQLContext => {
return {
user: {
id: 'test',
email: '[email protected]',
role: 'administrator',
}
}
}
});
})
it(`pluginNewsletterExport`, async () => {
const res = await server.executeOperation({
query: gql`
query pluginNewsletterExport {
pluginNewsletterExport {
email
}
}
`
});
const newsletters = res?.data?.pluginNewsletterExport;
expect(newsletters.length).toBe(2);
});
it(`pluginNewsletterStats`, async () => {
const res = await server.executeOperation({
query: gql`
query pluginNewsletterStats {
pluginNewsletterStats
}
`
});
const stats = res?.data?.pluginNewsletterStats;
expect(stats + '').toBe(2 + '');
});
})
Example #14
Source File: typegraphql-options-federation.factory.ts From typegraphql-nestjs with MIT License | 5 votes |
async createGqlOptions(): Promise<GqlModuleOptions> {
const { globalMiddlewares } = this.rootModuleOptions;
const {
resolversClasses,
container,
orphanedTypes,
featureModuleOptionsArray,
} = this.optionsPreparatorService.prepareOptions<TypeGraphQLFeatureFedarationModuleOptions>(
TYPEGRAPHQL_FEATURE_FEDERATION_MODULE_OPTIONS,
globalMiddlewares,
);
const referenceResolversArray = [...featureModuleOptionsArray].filter(
it => it.referenceResolvers,
);
const referenceResolvers =
referenceResolversArray.length > 0
? Object.fromEntries(
referenceResolversArray.flatMap(it =>
Object.entries(it.referenceResolvers!),
),
)
: undefined;
const baseSchema = await buildSchema({
...this.rootModuleOptions,
directives: [...specifiedDirectives, ...federationDirectives],
resolvers: resolversClasses as NonEmptyArray<ClassType>,
orphanedTypes,
container,
});
const schema = buildFederatedSchema({
typeDefs: gql(printSchema(baseSchema)),
resolvers: createResolversMap(baseSchema) as GraphQLResolverMap<any>,
});
if (referenceResolvers) {
addResolversToSchema(schema, referenceResolvers);
}
return {
...this.rootModuleOptions,
schema,
};
}
Example #15
Source File: newsletter.resolver.test.ts From Cromwell with MIT License | 5 votes |
describe('product-showcase.resolver', () => {
let server: ApolloServer;
beforeAll(async () => {
const schema = await buildSchema({
resolvers: [PluginProductShowcaseResolver],
validate: false,
authChecker: () => true,
});
server = new ApolloServer({
schema,
context: (): TGraphQLContext => {
return {
user: {
id: 'test',
email: '[email protected]',
role: 'administrator',
}
}
}
});
})
it(`pluginProductShowcase`, async () => {
const res = await server.executeOperation({
query: gql`
query pluginProductShowcase($slug: String) {
pluginProductShowcase(slug: $slug) {
elements {
name
}
}
}
`,
variables: { slug: null }
});
const data = res?.data?.pluginProductShowcase?.elements;
expect(data.length).toBe(2);
});
})
Example #16
Source File: index.ts From convoychat with GNU General Public License v3.0 | 4 votes |
async function bootstrap() {
const schema = await buildSchema({
resolvers: [
RoomResolver,
UserResolver,
ImageResolver,
MessageResolver,
InvitationResolver,
NotificationResolver,
MessageSubscriptions,
NotificationsSubscriptions,
],
emitSchemaFile: "./server/graphql/schema.gql",
globalMiddlewares: [TypegooseMiddleware],
scalarsMap: [{ type: ObjectID, scalar: ObjectIdScalar }],
authChecker: useAuth,
pubSub: pubsub,
});
const server = new ApolloServer({
schema: schema,
schemaDirectives: {
rateLimit: rateLimitDirective,
},
subscriptions: {
path: "/subscriptions",
// https://github.com/jkettmann/graphql-passport#usage-with-subscriptions
onConnect: createOnConnect([
sessionMiddleware,
passportMiddleware,
passportSessionMiddleware,
]) as any,
},
context: ({ req, res, connection }) => {
let context = connection && connection.context;
let currentUser = connection && connection.context.req.user;
if (!context) context = buildContext({ req, res });
if (!currentUser) {
currentUser = context.getUser();
}
try {
return {
...context,
pubsub,
currentUser,
};
} catch (err) {
throw new ApolloError(err);
}
},
uploads: {
// https://github.com/jaydenseric/graphql-upload#type-processrequestoptions
maxFileSize: 10000000, // 10 MB
maxFiles: 20,
},
playground: {
settings: {
"request.credentials": "include",
},
},
});
server.applyMiddleware({
app,
path: "/graphql",
onHealthCheck: () => {
return new Promise((resolve, reject) => {
if (mongoose.connection.readyState === 200) {
return resolve();
}
reject();
});
},
});
const httpServer = http.createServer(app);
server.installSubscriptionHandlers(httpServer);
// static client
app.use("/", expressStaticGzip("client/build", {}));
if (process.env.NODE_ENV === "production") {
app.get("/*", function (req, res) {
res.sendFile(
path.join(__dirname, "../client/build/index.html"),
function (err) {
if (err) {
res.status(500).send(err);
}
}
);
});
}
httpServer.listen({ port: 4000 }, () => {
mongoose.connect(
process.env.DB_URL as string,
{ useUnifiedTopology: true, useNewUrlParser: true },
err => {
if (err) throw err;
console.log("Connected to Database");
}
);
console.log("http://localhost:4000");
});
}
Example #17
Source File: index.ts From ExpressLRS-Configurator with GNU General Public License v3.0 | 4 votes |
async start(
config: IConfig,
logger: LoggerService,
port: number
): Promise<http.Server> {
const pubSub = new PubSub();
Container.set([{ id: ConfigToken, value: config }]);
Container.set([{ id: PubSubToken, value: pubSub }]);
Container.set([{ id: LoggerToken, value: logger }]);
const platformio = new Platformio(
config.getPlatformioPath,
config.platformioStateTempStoragePath,
config.PATH,
config.env,
logger
);
Container.set(
FirmwareService,
new FirmwareService(
config.PATH,
config.firmwaresPath,
platformio,
new FirmwareBuilder(platformio),
pubSub,
logger
)
);
Container.set(
UpdatesService,
new UpdatesService(
config.configuratorGit.owner,
config.configuratorGit.repositoryName
)
);
Container.set(
SerialMonitorService,
new SerialMonitorService(pubSub, logger)
);
const mDnsNotifications = new MulticastDnsNotificationsService(
pubSub,
logger
);
if (config.multicastDnsSimulatorEnabled) {
Container.set(
MulticastDnsService,
new MulticastDnsSimulatorService(mDnsNotifications)
);
} else {
Container.set(
MulticastDnsService,
new MulticastDnsService(mDnsNotifications, logger)
);
}
const deviceService = new DeviceService(logger);
await deviceService.loadFromFileSystemAt(config.devicesPath);
Container.set(DeviceService, deviceService);
if (config.userDefinesLoader === FirmwareParamsLoaderType.Git) {
Container.set(
UserDefinesBuilder,
new UserDefinesBuilder(
new GitUserDefinesLoader(
logger,
config.PATH,
config.userDefinesStoragePath
),
deviceService
)
);
} else if (config.userDefinesLoader === FirmwareParamsLoaderType.Http) {
Container.set(
UserDefinesBuilder,
new UserDefinesBuilder(new HttpUserDefinesLoader(logger), deviceService)
);
}
if (config.targetsLoader === FirmwareParamsLoaderType.Git) {
Container.set(
TargetsLoader,
new GitTargetsService(
logger,
deviceService,
config.PATH,
config.targetsStoragePath
)
);
} else if (config.targetsLoader === FirmwareParamsLoaderType.Http) {
Container.set(
TargetsLoader,
new HttpTargetsService(logger, deviceService)
);
} else {
throw new Error('FirmwareTargetsLoaderType is not set');
}
Container.set(LuaService, new LuaService(logger));
const schema = await buildSchema({
resolvers: [
FirmwareResolver,
SourcesResolver,
UpdatesResolver,
SerialMonitorResolver,
MulticastDnsMonitorResolver,
LuaResolver,
],
container: Container,
pubSub,
});
const server = new ApolloServer({
schema,
introspection: true,
});
this.app = express();
server.applyMiddleware({
app: this.app,
});
this.server = this.app.listen({ port });
/*
I know, crazy. It is 45 minutes, but on slower network connection it might take a while to download
and install all Platformio dependencies and build firmware.
*/
this.server.setTimeout(45 * 60 * 1000);
server.installSubscriptionHandlers(this.server);
return this.server;
}
Example #18
Source File: main.ts From Cromwell with MIT License | 4 votes |
async function bootstrap(): Promise<void> {
readCMSConfigSync();
await checkConfigs();
// Connect to DB via TypeOrm
await connectDatabase();
checkCmsVersion();
const envMode = loadEnv();
const authSettings = await getAuthSettings();
// Init Fastify as Nest.js server
const apiPrefix = 'api';
const fastifyInstance = fastify();
// GraphQL
const schema = await buildSchema({
resolvers: (await getResolvers()),
orphanedTypes: (await collectPlugins()).entities as any,
validate: false,
dateScalarMode: "isoDate",
authChecker: graphQlAuthChecker,
});
const apolloServer = new ApolloServer({
schema,
context: (context): TGraphQLContext => {
return { user: context?.request?.user }
},
debug: envMode.envMode === 'dev',
introspection: envMode.envMode === 'dev',
plugins: [
envMode.envMode === 'dev' ?
ApolloServerPluginLandingPageLocalDefault({ footer: false }) :
ApolloServerPluginLandingPageDisabled()
],
formatError: getErrorFormatter(envMode),
});
await apolloServer.start();
fastifyInstance.register(apolloServer.createHandler({
path: `/${apiPrefix}/graphql`,
cors: corsHandler,
}));
// JWT Auth
fastifyInstance.addHook('preHandler', async (request: any, reply) => {
await authServiceInst?.processRequest(request, reply);
});
// REST API
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter(fastifyInstance as any),
);
app.setGlobalPrefix(apiPrefix);
app.useGlobalFilters(new RestExceptionFilter());
// Plugins, extensions, etc.
fastifyInstance.register(require('fastify-cookie'), {
secret: authSettings.cookieSecret,
});
app.register(require('fastify-cors'), corsHandler);
if (envMode.envMode !== 'dev') {
app.register(require('fastify-helmet'));
app.register(require('fastify-csrf'));
}
app.register(require('fastify-multipart'));
app.useGlobalPipes(new ValidationPipe({ transform: true }));
// Setup SwaggerUI
if (envMode.envMode === 'dev') {
const options = new DocumentBuilder()
.setTitle('Cromwell API Server')
.setVersion('1.0.0')
.addBearerAuth()
.build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup(`/${apiPrefix}/api-docs`, app, document);
}
const port = parseInt(((await getPort({
port: getPort.makeRange(4032, 4063),
})) + '').replace(/[^0-9]/g, ''));
await app.listen((port && !isNaN(port)) ? port : 4032, '::');
logger.info(`API Server is running on: ${await app.getUrl()}`);
childRegister(port);
}