@nestjs/common#Injectable TypeScript Examples
The following examples show how to use
@nestjs/common#Injectable.
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: ft-auth.guard.ts From 42_checkIn with GNU General Public License v3.0 | 7 votes |
@Injectable()
export class FtAuthGuard extends AuthGuard('42') {
handleRequest(err, user, info, context: ExecutionContext) {
if (err || !user) {
const res = context.switchToHttp().getResponse();
return res.redirect('/');
}
return user;
}
}
Example #2
Source File: firebase-admin-database.service.ts From nestjs-firebase-admin with MIT License | 6 votes |
@Injectable()
export class FirebaseDatabaseService implements admin.database.Database {
app: FirebaseApp;
constructor(public readonly _app: admin.app.App) {}
get database() {
if (!this._app) {
throw new Error('Firebase instance is undefined.');
}
return this._app.database();
}
goOffline(): void {
return this.database.goOffline();
}
goOnline(): void {
return this.database.goOnline();
}
ref(path?: string | admin.database.Reference): admin.database.Reference {
return this.database.ref(path);
}
refFromURL(url: string): admin.database.Reference {
return this.database.refFromURL(url);
}
getRules(): Promise<string> {
return this.database.getRules();
}
getRulesJSON(): Promise<object> {
return this.database.getRulesJSON();
}
setRules(source: string | object | Buffer): Promise<void> {
return this.database.setRules(source);
}
useEmulator(host: string, port: number): void {
this.database.useEmulator(host, port);
}
}
Example #3
Source File: gcloud-multer.service.ts From nestjs-gcloud-storage with MIT License | 6 votes |
/**
* @todo This service is not working with the Multer API. Figure out why!
*/
@Injectable()
export class GCloudMulterStorageService {
// protected azureStorage: AzureStorageService;
constructor(
// @Inject(AZURE_STORAGE_MODULE_OPTIONS)
// private readonly options: AzureStorageOptions,
private readonly gcsStorage: GCloudStorageService,
) {
// Logger.log(this.azureStorage, 'AzureMulterStorageService');
// this.azureStorage = new AzureStorageService(options);
}
// @implement multer.storage
async _handleFile(_req: any, file: any, cb: Function) {
const storageUrl = await this.gcsStorage.upload(file);
file.storageUrl = storageUrl;
cb(null, {
file,
});
}
// @implement multer.storage
_removeFile(_req: any, file: any, cb: Function) {
delete file.buffer;
cb(null);
}
}
Example #4
Source File: app.service.ts From nr-apm-stack with Apache License 2.0 | 6 votes |
@Injectable()
export class AppService {
/**
* Handles the data received as a mock Kinesis event
* @param data The data to pass into the parser
* @param print If true, print the data to the console
* @returns Promise with the result
*/
handleKinesisEvent(@Body() data: OsDocumentData, print: boolean): Promise<OpenSearchBulkResult> {
return myContainer.get<KinesisStreamWrapperService>(TYPES.KinesisStreamWrapperService)
.handleData(data, print);
}
}
Example #5
Source File: auth-guards.ts From Cromwell with MIT License | 6 votes |
@Injectable()
export class JwtAuthGuard implements CanActivate {
constructor(private reflector: Reflector) { }
async canActivate(context: ExecutionContext): Promise<boolean> {
if (getStoreItem('cmsSettings')?.installed === false) return true;
const request: TRequestWithUser = context.switchToHttp().getRequest();
if (!request.user?.id) return false;
const roles = this.reflector.get<TAuthRole[]>('roles', context.getHandler());
return matchRoles(request.user, roles);
}
}
Example #6
Source File: hook-explorer.service.ts From nestjs-mercurius with MIT License | 6 votes |
@Injectable()
export class HookExplorerService extends BaseExplorerService {
constructor(
private readonly modulesContainer: ModulesContainer,
private readonly metadataScanner: MetadataScanner,
@Optional()
@Inject(GRAPHQL_MODULE_OPTIONS)
private readonly gqlOptions?: MercuriusModuleOptions,
) {
super();
}
explore() {
const modules = this.getModules(
this.modulesContainer,
this.gqlOptions?.include || [],
);
return this.flatMap(modules, (instance) => this.filterHooks(instance));
}
filterHooks<T = any>(wrapper: InstanceWrapper<T>) {
const { instance } = wrapper;
if (!instance) {
return undefined;
}
const prototype = Object.getPrototypeOf(instance);
return this.metadataScanner.scanFromPrototype(instance, prototype, (name) =>
extractHookMetadata(instance, prototype, name),
);
}
}
Example #7
Source File: application.service.ts From nest-nuxt-starter with MIT License | 6 votes |
@Injectable()
export class ApplicationService {
private readonly users: User[];
constructor() {
this.users = new Array(1000).fill(undefined).map((_, index) => ({
id: index + 1,
name: `user ${index + 1}`,
}));
}
async fetchAll(): Promise<User[]> {
return this.users;
}
async fetchOne(id: number): Promise<User> {
return this.users.find((user) => user.id === id);
}
}
Example #8
Source File: ormconfig.service.ts From nestjs-api-example with MIT License | 6 votes |
@Injectable()
export class TypeOrmConfigService implements TypeOrmOptionsFactory {
constructor(private configService: ConfigService) {}
createTypeOrmOptions(): TypeOrmModuleOptions {
return {
type: this.configService.get('DB_TYPE') as any,
host: this.configService.get('DB_HOST'),
port: parseInt(this.configService.get('DB_PORT')) || 3306,
username: this.configService.get('DB_USERNAME'),
password: this.configService.get('DB_PASSWORD'),
database: this.configService.get('DB_NAME'),
entities: [__dirname + '/../../**/*.entity{.ts,.js}'],
synchronize: this.configService.isEnv('development'),
logging: this.configService.isEnv('development'),
};
}
}
Example #9
Source File: status.service.ts From nest-react with GNU Lesser General Public License v3.0 | 6 votes |
@Injectable()
export class StatusService {
private logger = new Logger(StatusService.name);
private version: Dictionary<string>;
constructor(private readonly configService: ConfigService) {
this.version = readFileSync(
join(configService.rootDir, '..', '..', 'VERSION')
)
.toString()
.split(/[\r\n]+/)
.reduce((agg, line) => {
const [key, value] = line.split('=');
// The client is served from another Docker image
// thus, this one isn't necessarily correct
if (key !== 'CLIENT_VERSION') {
agg[key] = value;
}
return agg;
}, {} as Dictionary<string>);
}
getStatus(): string {
this.logger.log('log from statusService.getStatus()');
return `Status world from Nest running on ${this.configService.host}:${this.configService.port}!`;
}
getVersion(): Dictionary<string> {
return this.version;
}
}
Example #10
Source File: resolver.ts From typegraphql-nestjs with MIT License | 6 votes |
@Injectable()
@Resolver()
export default class RecipeResolver {
constructor(private readonly recipeService: RecipeService) {}
@Query(returns => [Recipe])
recipes() {
return this.recipeService.getRecipes();
}
@Mutation(returns => Recipe)
addRecipe(@Arg("input") recipe: Recipe) {
this.recipeService.addRecipe(recipe);
return recipe;
}
}
Example #11
Source File: app.service.ts From NestJs-youtube with MIT License | 6 votes |
@Injectable()
export class AppService extends Seed {
constructor(entityManager: EntityManager) {
super(entityManager);
this.fakeData();
}
getHello(): string {
return 'Hello World!';
}
private async fakeData(): Promise<void> {
// await this.fakeIt(UserEntity);
// await this.fakeIt(PostEntity);
// this.fakeIt(CommentEntity);
// this.fakeIt(LikeEntity);
// this.fakeIt(UserFollower);
}
}
Example #12
Source File: roles.guard.ts From nest-js-boilerplate with MIT License | 6 votes |
@Injectable()
export default class RolesGuard implements CanActivate {
constructor(
private reflector: Reflector,
) { }
async canActivate(context: ExecutionContext): Promise<boolean> {
const roles = this.reflector.get<string[]>('roles', context.getHandler());
if (!roles) {
return true;
}
const request: Request = context.switchToHttp().getRequest();
const user = request.user as UserDocument;
return user.role === RolesEnum.admin || roles.includes(user.role);
}
}