npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@tresdoce-nestjs-toolkit/qrcode

v0.0.2

Published

Tresdoce NestJS Toolkit - Módulo para crear códigos QR

Downloads

4

Readme

Este módulo está pensado para ser utilizado en NestJS Starter, o cualquier proyecto que utilice una configuración centralizada, siguiendo la misma arquitectura del starter.

Glosario


📝 Requerimientos básicos

🛠️ Instalar dependencia

npm install -S @tresdoce-nestjs-toolkit/qrcode
yarn add @tresdoce-nestjs-toolkit/qrcode

👨‍💻 Uso

El servicio QrCodeService tiene disponible la función createQrCode() que genera el código QR y lo retorna como URL en base64, y también cuenta con la función createQrCodeBuffer() la cual genera el código QR y lo retorna como imagen.

Para poder hacer uso de estas funcionalidades, es cuestión de importar el QrCodeModule en el módulo o bien inyectar el servicio QrCodeService en el provider del módulo, recomendable que sea en el módulo principal.

Importación de módulo

// ./src/app.module.ts
import { Module } from '@nestjs/common';
import { QrCodeModule } from '@tresdoce-nestjs-toolkit/qrcode';

@Module({
  //...
  imports: [
    //...
    QrCodeModule,
    //...
  ],
  //...
})
export class AppModule {}

Inyección de servicio

// ./src/app.module.ts
import { Module } from '@nestjs/common';
import { QrCodeService } from '@tresdoce-nestjs-toolkit/qrcode';

@Module({
  //...
  providers: [
    //...
    QrCodeService,
    //...
  ],
  //...
})
export class AppModule {}

Controllers

Dependiendo que tipo de código QR deseas retornar, la diferencia va a estar en el controlador de la aplicación.

// ./src/app.controller.ts
import { Controller, Get, Res } from '@nestjs/common';
import type { Response } from 'express';

import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  // Retorna URL en base64 del código QR
  @Get('qr-code-url')
  async createQrCodeUrl() {
    return await this.appService.createQrCodeUrl();
  }

  // Retorna imagen del código QR
  @Get('qr-code-buffer')
  async createQrCodeBuffer(@Res() response: Response) {
    const qrCodeBuffer = await this.appService.createQrCodeBuffer();
    response.status(200);
    response.type('image/png');
    response.send(qrCodeBuffer);
  }
}

Services

Inyectamos el QrCodeService en el constructor de nuestro service para poder hacer uso de las funcionalidades.

La función para crear códigos QR admite dos parámetros, data que es un objeto que contiene el tipo de contenido y sus valores y options que es un objeto para customizar el código QR ya sea tamaño, version, margin, color, etc., este servicio ya cuenta con una configuración base, la cual se puede reemplazar los valores enviando los nuevos atributos.

Para más información sobre las opciones disponibles pódes visitar la documentación de QRCode - Options

// ./src/app.service.ts
import { Inject, Injectable } from '@nestjs/common';
import { QrCodeService } from '@tresdoce-nestjs-toolkit/qrcode';

@Injectable()
export class AppService {
  constructor(@Inject(QrCodeService) private qrcode: QrCodeService) {}

  // Genera código QR como URL en base64
  async createQrCodeUrl(): Promise<string> {
    const options = {
      width: 300,
    };
    return await this.qrcode.createQrCode({ type: 'text', text: 'Hola Mundo' }, options);
  }

  // Genera código QR como Buffer
  async createQrCodeBuffer(): Promise<Buffer> {
    const options = {
      width: 300,
    };
    return await this.qrcode.createQrCodeBuffer({ type: 'text', text: 'Hola Mundo' }, options);
  }
}

Tipos de código QR

El módulo cuenta con la generación de diversos contenidos en el código QR que va a depender de la estructura y contenido de la data que le envies a la función, sea URL o Buffer.

Texto plano
createQrCode({ type: 'text', text: 'Hola Mundo' });
URL
createQrCode({ type: 'url', url: 'https://www.ejemplo.com' });
WIFI
createQrCode({
  type: 'wifi',
  ssid: 'MiWifi',
  password: 'password123',
  encryption: 'WPA',
});
vCard
createQrCode({
  type: 'vcard',
  name: 'Juan Perez',
  phone: '+34123456789',
  email: '[email protected]',
  organization: 'Ejemplo S.A.',
});
Email
createQrCode({
  type: 'email',
  address: '[email protected]',
  subject: 'Saludos',
  body: 'Hola, este es un email de ejemplo.',
});
SMS
createQrCode({
  type: 'sms',
  phone: '+34123456789',
  message: 'Hola, ¿cómo estás?',
});
Whatsapp
createQrCode({
  type: 'whatsapp',
  phone: '+34123456789',
  message: 'Hola, ¿cómo estás?',
});
Geolocalización
createQrCode({
  type: 'geo',
  latitude: -34.6395141,
  longitude: -58.4022226,
});
Evento
createQrCode({
  type: 'event',
  summary: 'Reunión de Trabajo',
  start: '20261015T170000Z',
  end: '20261015T190000Z',
});
Criptomoneda
createQrCode({
  type: 'crypto',
  currency: 'bitcoin',
  address: '1BoatSLRHtKNngkdXEeobR76b53LETtpyT',
});

📄 Changelog

Todos los cambios notables de este paquete se documentarán en el archivo Changelog.