简体   繁体   English

NodeJs:从具有类型定义的文件中读取并作为 class 定义写入文件

[英]NodeJs: read from file with type definitions and write to file as class definition

I have a typescript file with types definitions.我有一个带有类型定义的 typescript 文件。 I need to find for specific type name and write it to another file but as a class. For example:我需要找到特定的类型名称并将其写入另一个文件,但作为 class。例如:

type exampleOne = {
    atrA: string
    atrB: number
}
type exampleTwo = {
    atrA: number
    atrB: string
    atrC: string
}

and write exampleTwo to another file as:并将 exampleTwo 写入另一个文件:

class exampleTwo {
    atrA: number
    atrB: string
    atrC: string
}

I have this idea but I don't know how to implement it:我有这个想法,但我不知道如何实现它:

  1. read the file读取文件
  2. find the type name I want找到我想要的类型名称
  3. select from the beginning of the line where what I am looking for is, until the next closing bracket select 从我要查找的行的开头开始,直到下一个右括号
  4. replace the word 'type' by 'class' and suppress the equal sign用“class”替换单词“type”并取消等号
  5. write to another file写入另一个文件

you maybe are looking for this: https:\/\/www.typescriptlang.org\/docs\/handbook\/typescript-in-5-minutes.html<\/a>您可能正在寻找这个: https<\/a> :\/\/www.typescriptlang.org\/docs\/handbook\/typescript-in-5-minutes.html

in this case maybe you are trying typing something like this?在这种情况下,也许您正在尝试输入这样的内容?

class exampleTwo {
  atrA: number;
  atrB: string;
  atrC: string;

constructor(atrA: number, atrB: string, atrC: string)
  this.atrA = atrA;
  this.atrB = atrB;
  this.atrC = atrC;
}

const newExample = new exampleTwo(2, 'hello', 'world');

Since I don't found a way to solve this, I finally solved this by making my own script in bash. I could use javascript but I prefer bash:由于我没有找到解决这个问题的方法,我最终通过在 bash 中编写自己的脚本解决了这个问题。我可以使用 javascript,但我更喜欢 bash:

# Take as argument a name for reference
NEW=$1

# Verify argument is passed
if [ $# -ne 1 ]; then
    echo "One argument is required."
    exit 1
fi

# Location where the types are
PRISMA_URL='./node_modules/.prisma/client/index.d.ts'

# Location to save the file
NEW_DTO_CREATE_URL="./src/dtos/create-"${NEW}".dto.ts"

# Verify if already exists that file
if [ -f ${NEW_DTO_CREATE_URL} ]; then
    echo "Already exists"
else

  # Get the line number where starts the type I need
  LINE_N=$(grep -nm1 "export type ${NEW}CreateManyInput = {" ${PRISMA_URL} | grep -Po '^[^:]+')
  echo "export class Create${NEW^}Dto {" >> ${NEW_DTO_CREATE_URL}
  # Read all the line content on that line number
  LINE=$(head -n ${LINE_N} ${PRISMA_URL} | tail -1)

  # Start the loop. While LINE isn't a closed bracket...
  while [[ ${LINE} != *"}"* ]]; do
      ((LINE_N+=1))
      LINE=$(head -n ${LINE_N} ${PRISMA_URL} | tail -1)
      echo "${LINE}" >> ${NEW_DTO_CREATE_URL}
  done
fi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM