@nestjs/common#createParamDecorator TypeScript Examples

The following examples show how to use @nestjs/common#createParamDecorator. 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: user.decorator.ts    From life-helper-backend with MIT License 6 votes vote down vote up
User = createParamDecorator((data: undefined | keyof RequestUser, ctx: ExecutionContext) => {
  const request = ctx.switchToHttp().getRequest<ExtRequest>()

  const user = request.user

  if (data && typeof data === 'string' && typeof user === 'object') {
    return user[data]
  } else {
    return user
  }
})
Example #2
Source File: queue-role.decorator.ts    From office-hours with GNU General Public License v3.0 6 votes vote down vote up
QueueRole = createParamDecorator(
  async (data: unknown, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest();
    const queue = await QueueModel.findOne(request.params.queueId);
    const courseId = queue?.courseId;
    const user = await UserModel.findOne(request.user.userId, {
      relations: ['courses'],
    });

    const userCourse = user.courses.find((course) => {
      return Number(course.courseId) === Number(courseId);
    });

    if (!userCourse) {
      throw new NotFoundException(
        "cannot read propery 'role ' of undefined on user: " + user.id + user,
      );
    }
    return userCourse.role;
  },
)
Example #3
Source File: course-role.decorator.ts    From office-hours with GNU General Public License v3.0 6 votes vote down vote up
CourseRole = createParamDecorator(
  async (data: unknown, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest();
    const courseId = request.params.courseId;
    const user = await UserModel.findOne(request.user.userId, {
      relations: ['courses'],
    });

    const userCourse = user.courses.find((course) => {
      return Number(course.courseId) === Number(courseId);
    });
    return userCourse.role;
  },
)
Example #4
Source File: user.decorator.ts    From radiopanel with GNU General Public License v3.0 6 votes vote down vote up
User = createParamDecorator(// tslint:disable-line variable-name
	(path: string[] = [], context: ExecutionContext): unknown => {
		const request = context.switchToHttp().getRequest() as IncomingMessage;

		const jwtResult = jwt.decode(request.headers.authorization.replace('Bearer ', '')) as any;

		return propOr(null, 'user')(jwtResult);
	}
)
Example #5
Source File: tracing-context.decorator.ts    From nestjs-jaeger-tracing with MIT License 6 votes vote down vote up
Tracing = createParamDecorator(
  (key: keyof TracingData, context: ExecutionContext) => {
    const contextType = context.getType<GqlContextType>();
    let tracingData: TracingData;
    if (contextType === 'graphql') {
      const ctx = GqlExecutionContext.create(context);
      tracingData = ctx.getContext<TracingObject>().tracing;
    }
    if (contextType === 'http') {
      const ctx = context.switchToHttp();
      tracingData = ctx.getRequest<TracingObject>().tracing;
    }
    if (contextType === 'rpc') {
      const ctx = context.switchToRpc();
      tracingData = ctx.getContext<TracingObject>().tracing;
    }
    return key ? tracingData && tracingData[key] : tracingData;
  },
)
Example #6
Source File: gqlUserRoles.decorator.ts    From amplication with Apache License 2.0 6 votes vote down vote up
UserRoles = createParamDecorator(
  (data: string, context: ExecutionContext) => {
    const ctx = GqlExecutionContext.create(context);
    const request = ctx.getContext<{ req: { user: any } }>().req;
    if (!request.user) {
      return null;
    }
    return data ? request.user[data] : request.user.roles;
  }
)
Example #7
Source File: recaptcha-result.ts    From google-recaptcha with MIT License 6 votes vote down vote up
RecaptchaResult = createParamDecorator((data, context: ExecutionContext) => {
    switch (context.getType<'http' | 'graphql'>()) {
        case 'http':
            return context.switchToHttp().getRequest().recaptchaValidationResult;
        case 'graphql':
            const graphqlModule = loadModule('@nestjs/graphql', true);
            return graphqlModule.GqlExecutionContext.create(context).getContext().req?.connection?._httpMessage?.req?.recaptchaValidationResult;
        default:
            return null;
    }
})
Example #8
Source File: ip.address.decorator.ts    From api with GNU Affero General Public License v3.0 6 votes vote down vote up
IpAddress = createParamDecorator((data: string, ctx: ExecutionContext) => {
  let req

  if (ctx.getType<string>() === 'graphql') {
    req = GqlExecutionContext.create(ctx).getContext().req
  } else {
    req = ctx.switchToHttp().getRequest()
  }

  if (req.clientIp) {
    return req.clientIp
  }

  return getClientIp(req)
})
Example #9
Source File: user.decorator.ts    From api with GNU Affero General Public License v3.0 6 votes vote down vote up
User = createParamDecorator(
  (data: unknown, ctx: ExecutionContext) => {
    const user = GqlExecutionContext.create(ctx).getContext().req.user

    if (!user) {
      return null
    }

    return user
  },
)
Example #10
Source File: decorator.ts    From nestjs-paginate with MIT License 5 votes vote down vote up
Paginate = createParamDecorator((_data: unknown, ctx: ExecutionContext): PaginateQuery => {
    const request: Request = ctx.switchToHttp().getRequest()
    const { query } = request

    // Determine if Express or Fastify to rebuild the original url and reduce down to protocol, host and base url
    let originalUrl
    if (request.originalUrl) {
        originalUrl = request.protocol + '://' + request.get('host') + request.originalUrl
    } else {
        originalUrl = request.protocol + '://' + request.hostname + request.url
    }
    const urlParts = new URL(originalUrl)
    const path = urlParts.protocol + '//' + urlParts.host + urlParts.pathname

    const sortBy: [string, string][] = []
    const searchBy: string[] = []

    if (query.sortBy) {
        const params = !Array.isArray(query.sortBy) ? [query.sortBy] : query.sortBy
        for (const param of params) {
            if (isString(param)) {
                const items = param.split(':')
                if (items.length === 2) {
                    sortBy.push(items as [string, string])
                }
            }
        }
    }

    if (query.searchBy) {
        const params = !Array.isArray(query.searchBy) ? [query.searchBy] : query.searchBy
        for (const param of params) {
            if (isString(param)) {
                searchBy.push(param)
            }
        }
    }

    const filter = mapKeys(
        pickBy(
            query,
            (param, name) =>
                name.includes('filter.') &&
                (isString(param) || (Array.isArray(param) && (param as any[]).every((p) => isString(p))))
        ) as Dictionary<string | string[]>,
        (_param, name) => name.replace('filter.', '')
    )

    return {
        page: query.page ? parseInt(query.page.toString(), 10) : undefined,
        limit: query.limit ? parseInt(query.limit.toString(), 10) : undefined,
        sortBy: sortBy.length ? sortBy : undefined,
        search: query.search ? query.search.toString() : undefined,
        searchBy: searchBy.length ? searchBy : undefined,
        filter: Object.keys(filter).length ? filter : undefined,
        path,
    }
})
Example #11
Source File: context.ts    From ironfish-api with Mozilla Public License 2.0 5 votes vote down vote up
Context = createParamDecorator(
  (_data: unknown, context: ExecutionContext): BaseContext => {
    const request = context.switchToHttp().getRequest<Request>();
    return request.context;
  },
)
Example #12
Source File: req-context.decorator.ts    From nestjs-starter-rest-api with MIT License 5 votes vote down vote up
ReqContext = createParamDecorator(
  (data: unknown, ctx: ExecutionContext): RequestContext => {
    const request = ctx.switchToHttp().getRequest();

    return createRequestContext(request);
  },
)
Example #13
Source File: user.decorator.ts    From Phantom with MIT License 5 votes vote down vote up
User = createParamDecorator((data, req) => req.user)
Example #14
Source File: auth-user.decorator.ts    From bank-server with MIT License 5 votes vote down vote up
AuthUser = createParamDecorator(
  (data: unknown, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest();
    return request.user;
  },
)
Example #15
Source File: casl-subject.ts    From nest-casl with MIT License 5 votes vote down vote up
CaslSubject = createParamDecorator(async (data: unknown, context: ExecutionContext) => {
  return new SubjectProxy(await ContextProxy.create(context).getRequest());
})
Example #16
Source File: HttpUser.ts    From typescript-clean-architecture with MIT License 5 votes vote down vote up
HttpUser: () => any = createParamDecorator((data: unknown, ctx: ExecutionContext) => {
  const request: HttpRequestWithUser = ctx.switchToHttp().getRequest();
  return request.user;
})
Example #17
Source File: user.decorator.ts    From office-hours with GNU General Public License v3.0 5 votes vote down vote up
User = createParamDecorator<string[]>(
  async (relations: string[], ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest();
    return await UserModel.findOne(request.user.userId, { relations });
  },
)
Example #18
Source File: user.decorator.ts    From office-hours with GNU General Public License v3.0 5 votes vote down vote up
UserId = createParamDecorator(
  (data: unknown, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest();
    return Number(request.user.userId);
  },
)
Example #19
Source File: request-user.decorator.ts    From nestjs-angular-starter with MIT License 5 votes vote down vote up
RequestUser = createParamDecorator(
  (data: unknown, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest();
    return request.user;
  },
)
Example #20
Source File: get-user.decorator.ts    From pknote-backend with GNU General Public License v3.0 5 votes vote down vote up
GetUser = createParamDecorator(
  (data: unknown, ctx: ExecutionContext): UserInfo => {
    const req = ctx.switchToHttp().getRequest();
    console.log('user', req.user);
    return req.user;
  },
)
Example #21
Source File: userData.decorator.ts    From amplication with Apache License 2.0 5 votes vote down vote up
UserData = createParamDecorator<undefined, ExecutionContext, User>(
  (data, ctx: ExecutionContext) => userFactory(ctx)
)
Example #22
Source File: post.decorator.ts    From nestjs-api-example with MIT License 5 votes vote down vote up
Car = createParamDecorator(
  (data: string, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest();
    const car = request.car;

    return data ? car && car[data] : car;
  },
)
Example #23
Source File: auth-bearer.decorator.ts    From nest-js-boilerplate with MIT License 5 votes vote down vote up
AuthBearer = createParamDecorator(
  (data: unknown, ctx: ExecutionContext) => {
    const { headers } = ctx.switchToHttp().getRequest();

    return headers.authorization.split(' ')[1];
  },
)
Example #24
Source File: request-user.decorator.ts    From nest-js-boilerplate with MIT License 5 votes vote down vote up
RequestUser = createParamDecorator(
  (data: unknown, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest();
    return request.user as UserDocument;
  },
)
Example #25
Source File: request-user.decorator.ts    From nest-js-boilerplate with MIT License 5 votes vote down vote up
RequestUser = createParamDecorator(
  (data: unknown, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest();
    return request.user as User;
  },
)
Example #26
Source File: request-user.decorator.ts    From nest-js-boilerplate with MIT License 5 votes vote down vote up
RequestUser = createParamDecorator(
  (data: unknown, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest();
    return request.user as UserEntity;
  },
)
Example #27
Source File: request-user.decorator.ts    From nest-js-boilerplate with MIT License 5 votes vote down vote up
RequestUser = createParamDecorator(
  (data: unknown, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest();
    return request.user as UserEntity;
  },
)
Example #28
Source File: auth.decorator.ts    From svvs with MIT License 5 votes vote down vote up
SignIn = createParamDecorator((data: unknown, ctx: ExecutionContext) => {
  const args = ctx.getArgs()[1]

  return {username: args.username, password: args.password}
})
Example #29
Source File: user.decorator.ts    From svvs with MIT License 5 votes vote down vote up
CurrentUser = createParamDecorator((data: unknown, ctx: ExecutionContext) => {
  return ctx
})