nestjs中生成uuid
Posted 久天.
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了nestjs中生成uuid相关的知识,希望对你有一定的参考价值。
nodejs中有一个uuid的生成库uuid:https://www.npmjs.com/package/uuid,使用起来非常简单。
快速开始
要创建随机UUID,可以使用npm
或者yarn
安装uuid
库
1.使用npm或者yarn安装uuid
npm install uuid --save
或者
yarn add uuid
2. 服务端创建一个UUID
common.service.ts
import { Injectable } from '@nestjs/common';
import { v4 as uuidv4 } from 'uuid';
@Injectable()
export class DashboardService {
// 获取uuid
async getUuid(): Promise<any> {
try {
const data = uuidv4()
return data;
} catch (error) {
return {
code: 503,
msg: `Service error: ${error}`,
};
}
}
}
common.controller.ts
import { Controller, Get, UseInterceptors } from '@nestjs/common';
import { TransformInterceptor } from 'src/common/httpHandle/transform.interceptor';
import { CommonService } from "./common.service";
@Controller('/rest/common')
export class DashboardController {
constructor(private readonly commonService: CommonService ) {}
@Get('op/uuid')
@UseInterceptors(new TransformInterceptor())
async getUuid() {
return await this.commonService.getUuid()
}
}
3. 前端使用
api.ts
import request from '@/utils/request';
const DASHBOARD_URL = '/rest/common/op'
/**
* @description: 允许传入prefix,生成UUID
* @param {any} data prefix 选填 String 前置字符
* @return {*}
*/
export const getUuid = () => {
return request({
url: `${DASHBOARD_URL}/uuid`,
method: 'get'
})
}
demo.vue
import { getUuid } from '@/api/workbench'
import { IResp } from '@/api/types'
public async getUuid() {
const { data }: IResp = await getUuid()
}
以上是关于nestjs中生成uuid的主要内容,如果未能解决你的问题,请参考以下文章