Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'type-graphql' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
return contact.firstName || contact.name.split(" ")[0];
}
@FieldResolver(_ => String)
public lastName(@Root() contact: Contact) {
return (
contact.lastName ||
/* TODO: This approximation isn't accurate always */
contact.name
.split(" ")
.slice(1)
.join(" ")
);
}
@FieldResolver(_ => Image)
public image(@Root() contact: Contact, @Ctx() ctx: IContext) {
if (!contact.image) {
return {
url: "",
};
}
if (contact.image.url.startsWith("http")) {
return contact.image;
}
// FIXME: Figure out why ctx can be missing
return {
url: `${ctx ? ctx.mediaUrl : "/media"}/${contact.image.url}`,
};
}
}
// dynamic topic
@Mutation(() => Boolean)
async pubSubMutationToDynamicTopic(
@PubSub() pubSub: PubSubEngine,
@Arg('topic') topic: string,
@Arg('message', { nullable: true }) message?: string,
): Promise {
const payload: NotificationPayload = { id: ++this.autoIncrement, message };
await pubSub.publish(topic, payload);
return true;
}
@Subscription({
topics: ({ args }) => args.topic,
})
subscriptionWithFilterToDynamicTopic(
@Arg('topic') topic: string,
@Root() { id, message }: NotificationPayload,
): Notification {
console.log('topic:', topic);
return { id, message, date: new Date() };
}
}
async createFeatureFlag(
@Arg('data') data: FeatureFlagCreateInput,
@UserId() userId: string
): Promise {
return this.service.create(data, userId);
}
@Mutation(() => FeatureFlag)
async updateFeatureFlag(
@Args() { data, where }: FeatureFlagUpdateArgs,
@UserId() userId: string
): Promise {
return this.service.update(data, where, userId);
}
@Mutation(() => StandardDeleteResponse)
async deleteFeatureFlag(
@Arg('where') where: FeatureFlagWhereUniqueInput,
@UserId() userId: string
): Promise {
// TODO: deletes across all environments. Just takes project key and flag key
return this.service.delete(where, userId);
}
}
}
@Mutation(() => Post)
async createPost(@Arg('data') data: PostCreateInput, @UserId() userId: string): Promise {
return this.service.create(data, userId);
}
@Mutation(() => Post)
async updatePost(
@Args() { data, where }: PostUpdateArgs,
@UserId() userId: string
): Promise {
return this.service.update(data, where, userId);
}
@Mutation(() => [Post])
async createManyPosts(
@Args() { data }: PostCreateManyArgs,
@UserId() userId: string
): Promise {
return this.service.createMany(data, userId);
}
// @Mutation(() => StandardDeleteResponse)
// async deletePost(
// @Arg('where') where: PostWhereUniqueInput,
// @UserId() userId: string
// ): Promise {
// return this.service.delete(where, userId);
// }
}
featureFlagSegments(
@Root() featureFlag: FeatureFlag,
@Ctx() ctx: BaseContext
): Promise {
return ctx.dataLoader.loaders.FeatureFlag.featureFlagSegments.load(featureFlag);
}
@FieldResolver(() => [FeatureFlagUser])
featureFlagUsers(
@Root() featureFlag: FeatureFlag,
@Ctx() ctx: BaseContext
): Promise {
return ctx.dataLoader.loaders.FeatureFlag.featureFlagUsers.load(featureFlag);
}
@Query(() => [FeatureFlag])
async featureFlags(@Args() { where, orderBy, limit, offset }: FeatureFlagWhereArgs): Promise<
FeatureFlag[]
> {
return this.service.find(where, orderBy, limit, offset);
}
// Custom resolver that has it's own InputType and calls into custom service method
@Query(() => [String])
async featureFlagsForUser(@Arg('where') where: FeatureFlagsForUserInput): Promise {
return this.service.flagsForUser(where);
}
@Query(() => FeatureFlag)
async featureFlag(@Arg('where') where: FeatureFlagWhereUniqueInput): Promise {
return this.service.findOne(where);
}
import "reflect-metadata";
import {Query, Resolver, buildSchema} from "type-graphql";
import express, {Application} from "express";
import {ApolloServer} from "apollo-server-express";
import {GraphQLSchema} from "graphql";
@Resolver()
class HelloResolver {
@Query(() => String) // eslint-disable-line require-await
async helloWorld(): Promise {
return "Hello World!";
}
}
export const createApolloServer = async (): Promise => {
const schema: GraphQLSchema = await buildSchema({resolvers: [HelloResolver]});
const apolloServer: ApolloServer = new ApolloServer({
schema,
playground: true,
});
return apolloServer;
};
import { ResetPasswordInput } from "./inputs/resetPassword.input"
import { cookieName } from "../../lib/config"
import { UserRepository } from "./user.repository"
import { CurrentUser } from "../shared/middleware/currentUser"
@Resolver(() => User)
export class UserResolver {
constructor(
private readonly userService: UserService,
private readonly userRepository: UserRepository,
private readonly userMailer: UserMailer,
) {}
// ME
@Authorized()
@Query(() => User, { nullable: true })
async me(@CurrentUser() currentUser: User): Promise {
return currentUser
}
// REGISTER
@Mutation(() => User)
async register(
@Arg("data") data: RegisterInput,
@Ctx() { req }: ResolverContext,
): Promise {
const user = await this.userService.create(data)
if (req.session) req.session.user = user
this.userMailer.sendWelcomeEmail(user)
return user
}
featureFlagUsers(
@Root() featureFlag: FeatureFlag,
@Ctx() ctx: BaseContext
): Promise {
return ctx.dataLoader.loaders.FeatureFlag.featureFlagUsers.load(featureFlag);
}
@Query(() => [FeatureFlag])
async featureFlags(@Args() { where, orderBy, limit, offset }: FeatureFlagWhereArgs): Promise<
FeatureFlag[]
> {
return this.service.find(where, orderBy, limit, offset);
}
// Custom resolver that has it's own InputType and calls into custom service method
@Query(() => [String])
async featureFlagsForUser(@Arg('where') where: FeatureFlagsForUserInput): Promise {
return this.service.flagsForUser(where);
}
@Query(() => FeatureFlag)
async featureFlag(@Arg('where') where: FeatureFlagWhereUniqueInput): Promise {
return this.service.findOne(where);
}
@Mutation(() => FeatureFlag)
async createFeatureFlag(
@Arg('data') data: FeatureFlagCreateInput,
@UserId() userId: string
): Promise {
return this.service.create(data, userId);
}
import { BaseContext, BaseResolver, StandardDeleteResponse } from '../../../src';
import {
PostCreateInput,
PostUpdateArgs,
PostWhereArgs,
PostWhereInput,
PostWhereUniqueInput
} from '../generated';
import { Post } from './post.model';
import { User } from './user.model';
// Note: we have to specify `Post` here instead of (() => Post) because for some reason this
// changes the object reference when it's trying to add the FieldResolver and things break
@Resolver(Post)
export class PostResolver extends BaseResolver {
constructor(@InjectRepository(Post) public readonly postRepository: Repository) {
super(Post, postRepository);
}
@FieldResolver(() => User)
user(@Root() post: Post, @Ctx() ctx: BaseContext): Promise {
return ctx.dataLoader.loaders.Post.user.load(post);
}
@Query(() => [Post])
async posts(@Args() { where, orderBy, limit, offset }: PostWhereArgs): Promise {
return this.find(where, orderBy, limit, offset);
}
@Query(() => Post)
import { ResolverContext } from "../../lib/types"
import { createToken, decryptToken } from "../../lib/jwt"
import { User } from "./user.entity"
import { UserService } from "./user.service"
import { UserMailer } from "./user.mailer"
import { RegisterInput } from "./inputs/register.input"
import { LoginInput } from "./inputs/login.input"
import { UpdateInput } from "./inputs/update.input"
import { ResetPasswordInput } from "./inputs/resetPassword.input"
import { UserRepository } from "./user.repository"
import { CurrentUser } from "../shared/middleware/currentUser"
import { SlackService } from "../shared/slack.service"
@Resolver(() => User)
export class UserResolver {
constructor(
private readonly userService: UserService,
private readonly userRepository: UserRepository,
private readonly userMailer: UserMailer,
private readonly slackService: SlackService,
) {}
// ME
@Authorized()
@Query(() => User, { nullable: true })
me(@CurrentUser() currentUser: User): Promise {
return this.userRepository.findById(currentUser.id)
}
// REGISTER