Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
RelayedQueryTypedDescriptor<
Through extends (undefined | null) ? Model : Through,
Through extends (undefined | null) ? never : true
>
>,
to: ClassValueThunk,
through?: ClassValueThunk,
options?: RelayedQueryOptions,
isFieldResolver: boolean = false
): void {
const queryName = this.getQueryName(propertyKey, options)
const { Connection } = this.makeEdgeConnection(to, through)
this.registerArgs(target, propertyKey, options)
const middleware = RelayFromArrayCountFactory(target, propertyKey);
UseMiddleware(middleware)(target, propertyKey, descriptor)
if(isFieldResolver) {
FieldResolver(() => Connection, { ...options, name: queryName })(target, propertyKey, descriptor)
} else {
Query(() => Connection, { ...options, name: queryName })(target, propertyKey, descriptor)
}
}
@UseMiddleware(isAuth)
@Mutation(() => returnType, { name: `updateBy${suffix}ID` })
async updateByID(@Arg('data', () => inputTypes.update) data: any, @Arg('id') id: string): Promise {
const entityData = await this.get(id);
return this.update(data, entityData);
}
@UseMiddleware(isAuth)
@Mutation(() => [returnType], { name: `createMulti${suffix}` })
async createMulti(@Arg('data', () => [inputTypes.create]) data: any[]): Promise {
const promises = data.map(obj => entity.create(obj).save());
const insertedData = await Promise.all(promises);
return insertedData;
}
@UseMiddleware(isAuth)
@Mutation(() => Boolean, { name: `deleteBy${suffix}ID` })
async deleteByID(@Arg('id', () => String) id: string): Promise {
const _entity = await this.get(id);
if (!_entity) {
sendError(`No data found on Entity: ${suffix}, ID: ${id}`);
}
const data = await entity.remove(_entity);
if (middlewares && middlewares.delete.after) {
await middlewares.delete.after(id);
}
return !!data;
}
async update(data: any, entityData: any): Promise {
for (const field in data) {
import { Resolver, Query, Mutation, Arg, UseMiddleware } from "type-graphql";
import bcrypt from "bcryptjs";
import { User } from "../../entity/User";
import { RegisterInput } from "./register/RegisterInput";
import { isAuth } from "../middleware/isAuth";
import { logger } from "../middleware/logger";
import { sendEmail } from "../utils/sendEmail";
import { createConfirmationUrl } from "../utils/createConfirmationUrl";
@Resolver()
export class RegisterResolver {
@UseMiddleware(isAuth, logger)
@Query(() => String)
async hello() {
return "Hello World!";
}
@Mutation(() => User)
async register(@Arg("data")
{
email,
firstName,
lastName,
password
}: RegisterInput): Promise {
const hashedPassword = await bcrypt.hash(password, 12);
const user = await User.create({
commentId,
questionId,
userToNotifyId: req.session && req.session.userId,
},
{
read,
}
);
return {
ok: true,
};
}
@Mutation(() => OkResponse)
@UseMiddleware(isAuthenticated)
async markAllNotificationsAsRead(@Ctx() { req }: MyContext): Promise<
OkResponse
> {
await this.questionCommentNotificationRepo.update(
{
userToNotifyId: req.session && req.session.userId,
},
{
read: true,
}
);
return {
ok: true,
};
}
export function Authorized(ruleFn?: any) {
return UseMiddleware(
async ({ args, context, info }: { args: any; context: Context; info: any }, next) => {
const { session = {} } = info || {};
if (!context.user && !session.user) {
throw new AuthenticationError('Must be authenticated');
}
if (ruleFn) {
ruleFn(
{
can: (action: string, subject: any, field?: string) => {
context.ability.throwUnlessCan(action, subject, field);
},
},
args
);
}
export function createBaseResolver(
suffix: string,
entity: any,
inputTypes: { create: classType; update: classType; filter?: classType },
returnType: classType,
middlewares?: MiddlewareBaseResolver
): any {
@Resolver({ isAbstract: true })
abstract class BaseResolver {
@UseMiddleware(isAuth)
@Query(() => [returnType], { name: `getAll${suffix}` })
async getAll(): Promise {
return entity.find();
}
@UseMiddleware(isAuth)
@Query(() => [returnType], { name: `getAll${suffix}Filter` })
async getAllFiltered(@Arg('data', () => inputTypes.filter || inputTypes.create) data: any): Promise {
return entity.find({ where: data });
}
@UseMiddleware(isAuth)
@Query(() => [returnType], { name: `getAll${suffix}Paginate` })
async getAllPagination(@Arg('data', () => PaginationQL) data: PaginationQL): Promise {
const { skip, take } = normalizePagination(data);
return entity.find({ skip, take });
): any {
@Resolver({ isAbstract: true })
abstract class BaseResolver {
@UseMiddleware(isAuth)
@Query(() => [returnType], { name: `getAll${suffix}` })
async getAll(): Promise {
return entity.find();
}
@UseMiddleware(isAuth)
@Query(() => [returnType], { name: `getAll${suffix}Filter` })
async getAllFiltered(@Arg('data', () => inputTypes.filter || inputTypes.create) data: any): Promise {
return entity.find({ where: data });
}
@UseMiddleware(isAuth)
@Query(() => [returnType], { name: `getAll${suffix}Paginate` })
async getAllPagination(@Arg('data', () => PaginationQL) data: PaginationQL): Promise {
const { skip, take } = normalizePagination(data);
return entity.find({ skip, take });
}
@UseMiddleware(isAuth)
@Query(() => returnType, { name: `get${suffix}` })
async get(@Arg('id', () => String) id: string): Promise {
return entity.findOne(id);
}
@UseMiddleware(isAuth)
@Mutation(() => returnType, { name: `create${suffix}` })
async create(@Arg('data', () => inputTypes.create) data: any): Promise {
if (middlewares && middlewares.create.before) {
import { QuestionCommentNotification } from "../../entity/QuestionCommentNotification";
import { MyContext } from "../../types/Context";
import { isAuthenticated } from "../shared/middleware/isAuthenticated";
import { OkResponse } from "../shared/OkResponse";
import { NotificationsResponse } from "./response";
const NOTIF_LIMIT = 50;
@Resolver(Comment)
export class CommentResolver {
@InjectRepository(QuestionCommentNotification)
private readonly questionCommentNotificationRepo: Repository<
QuestionCommentNotification
>;
@Query(() => NotificationsResponse)
@UseMiddleware(isAuthenticated)
async notifications(
@Ctx() { req }: MyContext,
@Arg("cursor", { nullable: true }) cursor?: string
): Promise {
const where: FindOneOptions["where"] = {
userToNotifyId: req.session && req.session.userId,
};
if (cursor) {
where.createdAt = LessThan(cursor);
}
const notifs = await this.questionCommentNotificationRepo.find({
where,
relations: ["comment", "question", "question.post"],
order: { read: "ASC", createdAt: "DESC" },
import { isAuthenticated } from "../shared/middleware/isAuthenticated";
import { CreatePostInput } from "./createInput";
import { FindPostInput } from "./findInput";
import { FindPostResponse } from "./findResponse";
import { PostResponse } from "./response";
const POST_LIMIT = 6;
@Resolver(Post)
export class PostResolvers {
@InjectRepository(QuestionRepository)
private readonly questionRepo: QuestionRepository;
@InjectRepository(PostRepository)
private readonly postRepo: PostRepository;
@Mutation(() => PostResponse)
@UseMiddleware(isAuthenticated)
async findOrCreatePost(
@Arg("post") input: CreatePostInput,
@Ctx() { req }: MyContext
): Promise {
let value = await this.postRepo.findOne({
where: {
commitId: input.commitId,
repo: input.repo,
repoOwner: input.repoOwner,
},
});
if (!value) {
value = await this.postRepo.save({
...input,
creatorId: req.session && req.session.userId,
export const createResolver = (
entity: any,
inputType: IInputType,
middleware?: Middleware[]
) => {
@Resolver()
class BaseResolver {
@Mutation(() => entity, { name: `create${entity.className}` })
@UseMiddleware(...(middleware || []))
create(@Arg('data', () => inputType) data: any, @Ctx() ctx: IAppContext) {
if (entity.belongsToUser) {
return entity
.create({
...data,
userConnection: { id: ctx.req.session.userId },
})
.save()
}
return entity.create(data).save()
}
}
return BaseResolver
}