generator-magic-node

0.1.0-dev.27 • Public • Published

generator-magic-node

License npm Gitter Join the chat at https://gitter.im/ant-design/ant-design

English | 简体中文

Describe

This is a node background service generator that generates framework and entity classes.

In order to ensure that the background required for a set of front-end projects can switch seamlessly between jhipster and nodejs, the interface specification and jhipster are as consistent as possible, including authorization and authentication methods.

Conditions

  1. yeoman needs to be installed.
npm install -g yo
  1. The entity class generation section requires the JSON file generated using [JDL], Those who are not familiar with JDL can find relevant documents and help on jhipster official website.
npm install -g generator-jhipster

Install

npm install -g generator-magic-node

Use

  • Generating scaffold.

    mkdir node-project
    cd node-project
    yo magic-node
    
  • Generating entity classes.

    1. Please go to jdl-studio to write the data table and export it to the project root directory. For example, the file I exported is jhipster-jdl.jh

          cp jhipster-jdl.jh node-project/jhipster-jdl.jh
          cd node-project
          jhipster import-jdl jhipster-jdl.jh
      

      After successful execution, .jhipster folder will appear in the current project file directory.

    2. Execute the command to generate the entity class.

      yo magic-node --lang=zh --entity=Region
      

      Or

      yo magic-node
      language[en/zh/ja] en
      What generates? Entity class
      Entity name: Region
      
    3. Run project.

      npm install tsc -g
      npm install
      npm run start
      
  • Entity profile templates

    .jhipster/Region.json

    {
      "javadoc": "region",
      "name": "Region",
      "fields": [
        {
          "javadoc": "name",
          "fieldName": "name",
          "fieldType": "String",
          "fieldValidateRules": [
            "required",
            "maxlength"
          ],
          "fieldValidateRulesMaxlength": 64
        },
        {
          "javadoc": "create time",
          "fieldName": "createTime",
          "fieldType": "Instant",
          "fieldValidateRules": ["required"]
        },
        {
          "javadoc": "update time",
          "fieldName": "updateTime",
          "fieldType": "Instant",
          "fieldValidateRules": ["required"]
        },
        {
          "javadoc": "is visible",
          "fieldName": "isVisible",
          "fieldType": "Boolean",
          "fieldValidateRules": ["required"]
        },
        {
          "javadoc": "is delete",
          "fieldName": "isDelete",
          "fieldType": "Boolean",
          "fieldValidateRules": ["required"]
        }
      ],
      "relationships": [],
      "changelogDate": "20190706100248",
      "entityTableName": "region",
      "dto": "mapstruct",
      "pagination": "pagination",
      "service": "serviceImpl",
      "jpaMetamodelFiltering": true,
      "fluentMethods": true,
      "clientRootFolder": "",
      "applications": "*"
    }
    

Directory structure

.directory
.gitignore
.jhipster   # Data model config.
│-- Region.json 
.yo-rc.json
README.md
config.json
ormconfig.json
package.json
src
│-- controller  # Control layer, interface entry.
│-- entity  # Entity layer, data model class location.
│-- enum  # Enum class.
│-- index.ts
│-- middleware
│-- migration
│-- sample  # Sample data for automatically creating template data at project startup.
│-- subscriber
│-- util
tsconfig.json

Generated control layer example

import { Context } from 'koa';
import { getManager } from 'typeorm';
import Region from '../entity/Region';
import { validate } from 'class-validator';
import Elastic from '../util/Elastic';
import { setRoute, RequestMethod } from '../middleware/Routes';
import { getElasticSearchParams, setElasticSearchPagingHeader, deleteSuccessfulResponse, getRequestParamId } from '../util/Tools';
import { BadRequestAlertException, NotFoundAlertException } from '../middleware/RequestError';

export default class RegionAction {
  /**
   * get
   * @param {Application.Context} context
   * @param decoded
   * @returns {Promise<void>}
   */
  @setRoute('/api/regions/:id')
  async getRegion(context: Context, decoded?: any) {
    const id = getRequestParamId(context);
    const regionRepository = getManager().getRepository(Region);
    const region: Region = await regionRepository.findOne(id);
    if (region) {
      context.body = region;
    } else {
      throw new NotFoundAlertException();
    }
  }
  /**
   * post
   * @param {Application.Context} context
   * @param decoded
   * @returns {Promise<void>}
   */
  @setRoute('/api/regions', RequestMethod.POST)
  async createRegion(context: Context, decoded?: any) {
    const regionRepository = getManager().getRepository(Region);
    let region: Region = regionRepository.create(<Region>{
      ...context.request.body
    });
    const errors = await validate(region);
    if (errors.length > 0) {
      throw new BadRequestAlertException(null, errors);
    } else {
      await getManager().save(region);
      region = await regionRepository.findOne(region.id);
      await Elastic.syncCreate(region, regionRepository.metadata.tableName);
      context.body = region;
    }
  }
  /**
   * put
   * @param {Application.Context} context
   * @param decoded
   * @returns {Promise<void>}
   */
  @setRoute('/api/regions', RequestMethod.PUT)
  async updateRegion(context: Context, decoded?: any) {
    const regionRepository = getManager().getRepository(Region);
    let region: Region = regionRepository.create(<Region>{
      ...context.request.body
    });
    const errors = await validate(region);
    if (errors.length > 0) {
      throw new BadRequestAlertException(null, errors);
    } else {
      await regionRepository.update(region.id, region);
      region = await regionRepository.findOne(region.id);
      await Elastic.syncUpdate(region, regionRepository.metadata.tableName);
      context.body = region;
    }
  }
  /**
   * delete
   * @param {Application.Context} context
   * @param decoded
   * @returns {Promise<void>}
   */
  @setRoute('/api/regions/:id', RequestMethod.DELETE)
  async deleteRegion(context: Context, decoded?: any) {
    const id = getRequestParamId(context);
    const regionRepository = getManager().getRepository(Region);
    await regionRepository.delete(id);
    await Elastic.syncDelete(id, regionRepository.metadata.tableName);
    deleteSuccessfulResponse(context, id)
  }
  /**
   * find
   * @param {Application.Context} context
   * @param decoded
   * @returns {Promise<void>}
   */
  @setRoute('/api/regions')
  async findRegion(context: Context, decoded?: DecodedUserInfo) {
    const fields = [
      'id',
      'regionName'
    ];
    const regionRepository = getManager().getRepository(Region);
    const condition: any = {
      where: createSearchSqlRepositoryBody(context.request.query, fields)
    };
    const count = await regionRepository.count(condition);
    setRepositoryPagingParams(condition, getSqlSearchPagingParams(context));
    const list = await regionRepository.find(condition);
    setSqlSearchPagingHeader(context, count);
    context.body = list;
  }
  /**
   * search
   * @param {Application.Context} context
   * @param decoded
   * @returns {Promise<void>}
   */
  @setRoute('/api/_search/regions')
  async searchRegion(context: Context, decoded?: any) {
    const res: any = await Elastic.search(getElasticSearchParams(context), 'region');
    setElasticSearchPagingHeader(context, res);
    context.body = res.data;
  }
}

Interface example

  • Create
    Request:

    curl --request POST \
    --url http://localhost:3000/api/regions \
    --header 'cache-control: no-cache' \
    --header 'content-type: application/json' \
    --header 'postman-token: 137cfaa2-bba3-94c6-a73d-858bf899f3c7' \
    --data '{\n	"regionName": "CN"\n}'
    
    POST /api/regions HTTP/1.1
    Host: localhost:3000
    Content-Type: application/json
    Cache-Control: no-cache
    Postman-Token: ffe8ff8c-f9e2-60be-dc1a-0f7e5e2b2383
    
    {
        "regionName": "CN"
    }
    

    Response:

    {
        "regionName": "CN",
        "id": 1
    }
    
  • Change
    Request:

    curl --request PUT \
    --url http://localhost:3000/api/regions \
    --header 'cache-control: no-cache' \
    --header 'content-type: application/json' \
    --header 'postman-token: e4cae952-07bc-0857-73be-9d2099d3954f' \
    --data '{\n	"id": 1,\n	"regionName": "JP"\n}'
    
    PUT /api/regions HTTP/1.1
    Host: localhost:3000
    Content-Type: application/json
    Cache-Control: no-cache
    Postman-Token: 604881ef-c221-f756-e3c5-6e1e58163b6c
    
    {
        "id": 1,
        "regionName": "JP"
    }
    

    Response:

    {
        "id": 1,
        "regionName": "JP"
    }
    
  • Delete
    Request:

    curl --request DELETE \
    --url http://localhost:3000/api/regions/1 \
    --header 'cache-control: no-cache' \
    --header 'content-type: application/json' \
    --header 'postman-token: d0bd6631-b56d-3c14-565a-f1a6d14aba47'
    
    DELETE /api/regions/1 HTTP/1.1
    Host: localhost:3000
    Content-Type: application/json
    Cache-Control: no-cache
    Postman-Token: 70b023ea-b101-c46e-9240-90f1909c2107
    

    Response:

    {
        "id": "1"
    }
    
  • Get
    Request:

    curl --request GET \
    --url http://localhost:3000/api/regions/1 \
    --header 'cache-control: no-cache' \
    --header 'content-type: application/json' \
    --header 'postman-token: 32045bad-4ed5-fbfa-4a7f-9b2686eb3891'
    
    GET /api/regions/1 HTTP/1.1
    Host: localhost:3000
    Content-Type: application/json
    Cache-Control: no-cache
    Postman-Token: ca50cf1d-7e72-70a2-37c8-037bfcc5893f
    
    

    Response:

    {
        "id": 1,
        "regionName": "CN"
    }
    
  • Search (use Elasticsearch)
    Query parameters:

    • query: Query string, please go to elastic for relevant documents.
    • page: Page index, Starting from the 0, default 0.
    • size: Page size, default 0.
    • sort: Sort,Please go to elastic for relevant documents.

    Request:

    curl --request GET \
    --url 'http://localhost:3000/api/_search/regions?query=regionName%3ACN&page=0&size=10' \
    --header 'cache-control: no-cache' \
    --header 'content-type: application/json' \
    --header 'postman-token: 12afa220-9d89-6f7c-97b9-1dde9f4c8c85'
    
    GET /api/_search/regions?query=regionName:CN&amp;page=0&amp;size=10 HTTP/1.1
    Host: localhost:3000
    Content-Type: application/json
    Cache-Control: no-cache
    Postman-Token: 260f20fc-4697-51a1-38cb-ceeb4259ea23
    

    Response:
    header

    x-page: 0
    x-size: 10
    x-total-count: 1
    

    body

    [
        {
            "id": 1,
            "regionName": "CN"
        }
    ]
    
  • Search (use Mysql)
    Query parameters:

    • *.equals: Condition, example: regionName.equals=CN.
    • *.contains: Condition.
    • *.in: Condition, example.in=1,2,3.
    • *.specified: Condition, example: name.specified=true.
    • *.greaterOrEqualThan: Condition, example: id.greaterOrEqualThan=2.
    • *.greaterThan: Condition.
    • *.lessOrEqualThan: Condition.
    • *.lessThan: Condition.
    • page: Page index, Starting from the 0, default 0.
    • size: Page size, default 0.
    • sort: Sort, example: sort=id,DESC&sort=regionName,ASC

    Request:

    curl --request GET \
    --url 'http://localhost:3000/api/_search/regions?regionName.equals=CN&sort=id%2CDESC&page=0&size=10' \
    --header 'cache-control: no-cache' \
    --header 'content-type: application/json' \
    --header 'postman-token: 2bee9d1e-d406-a8fc-47fb-01f0cd5a661a'
    
    GET /api/_search/regions?regionName.equals=CN&amp;sort=id,DESC&amp;page=0&amp;size=10 HTTP/1.1
    Host: localhost:3000
    Content-Type: application/json
    Cache-Control: no-cache
    Postman-Token: 88a2fc33-7d21-7395-ee59-d09c2399c571
    

    Response:
    header

    x-page: 0
    x-size: 10
    x-total-count: 1
    

    body

    [
        {
            "id": 1,
            "regionName": "CN"
        }
    ]
    

Login

Authorize the use of the JWT protocol, The interface is the same as jhipster's JWT authorized login interface.

  • Get Token
    Request:

    curl --request POST \
    --url http://localhost:3000/api/authenticate \
    --header 'cache-control: no-cache' \
    --header 'content-type: application/json' \
    --header 'postman-token: dd8547b8-5c18-e5b1-e0e9-621de99914f1' \
    --data '{\n	"password": "admin",\n	"username": "admin"\n}'
    
    POST /api/authenticate HTTP/1.1
    Host: localhost:3000
    Content-Type: application/json
    Cache-Control: no-cache
    Postman-Token: 53e4cacc-d444-ed3c-be50-c107693b8d1e
    
    {
        "password": "admin",
        "username": "admin"
    }
    

    Response:

    {
        "id_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImlkIjozLCJsb2dpbiI6ImFkbWluIiwiZmlyc3ROYW1lIjoiQWRtaW5pc3RyYXRvciIsImxhc3ROYW1lIjoiQWRtaW5pc3RyYXRvciIsImVtYWlsIjoiYWRtaW5AbG9jYWxob3N0IiwiaW1hZ2VVcmwiOiJodHRwczovL3dwaW1nLndhbGxzdGNuLmNvbS9mNzc4NzM4Yy1lNGY4LTQ4NzAtYjYzNC01NjcwM2I0YWNhZmUuZ2lmP2ltYWdlVmlldzIvMS93LzgwL2gvODAiLCJhY3RpdmF0ZWQiOjEsImxhbmdLZXkiOiJlbiIsImFjdGl2YXRpb25LZXkiOm51bGwsInJlc2V0S2V5IjpudWxsLCJjcmVhdGVkQnkiOiJzeXN0ZW0iLCJjcmVhdGVkRGF0ZSI6bnVsbCwicmVzZXREYXRlIjpudWxsLCJsYXN0TW9kaWZpZWRCeSI6InN5c3RlbSIsImxhc3RNb2RpZmllZERhdGUiOm51bGx9LCJhdXRob3JpdGllcyI6WyJST0xFX0FETUlOIiwiUk9MRV9VU0VSIl0sImlhdCI6MTU0ODM5OTQzNCwiZXhwIjoxNTQ5Njk1NDM0fQ.9y9YOKtJaT33T56A2mKKrSeI0ojCmUFPU5JxvLNR3ds"
    }
    
  • Get Account info
    Request:

    curl --request GET \
    --url http://localhost:3000/api/account \
    --header 'authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImlkIjozLCJsb2dpbiI6ImFkbWluIiwiZmlyc3ROYW1lIjoiQWRtaW5pc3RyYXRvciIsImxhc3ROYW1lIjoiQWRtaW5pc3RyYXRvciIsImVtYWlsIjoiYWRtaW5AbG9jYWxob3N0IiwiaW1hZ2VVcmwiOiJodHRwczovL3dwaW1nLndhbGxzdGNuLmNvbS9mNzc4NzM4Yy1lNGY4LTQ4NzAtYjYzNC01NjcwM2I0YWNhZmUuZ2lmP2ltYWdlVmlldzIvMS93LzgwL2gvODAiLCJhY3RpdmF0ZWQiOjEsImxhbmdLZXkiOiJlbiIsImFjdGl2YXRpb25LZXkiOm51bGwsInJlc2V0S2V5IjpudWxsLCJjcmVhdGVkQnkiOiJzeXN0ZW0iLCJjcmVhdGVkRGF0ZSI6bnVsbCwicmVzZXREYXRlIjpudWxsLCJsYXN0TW9kaWZpZWRCeSI6InN5c3RlbSIsImxhc3RNb2RpZmllZERhdGUiOm51bGx9LCJhdXRob3JpdGllcyI6WyJST0xFX0FETUlOIiwiUk9MRV9VU0VSIl0sImlhdCI6MTU0ODM5OTQzNCwiZXhwIjoxNTQ5Njk1NDM0fQ.9y9YOKtJaT33T56A2mKKrSeI0ojCmUFPU5JxvLNR3ds' \
    --header 'cache-control: no-cache' \
    --header 'postman-token: bc7974d7-c9ff-8ccb-1037-0efdb099db88'
    
    GET /api/account HTTP/1.1
    Host: localhost:3000
    Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImlkIjozLCJsb2dpbiI6ImFkbWluIiwiZmlyc3ROYW1lIjoiQWRtaW5pc3RyYXRvciIsImxhc3ROYW1lIjoiQWRtaW5pc3RyYXRvciIsImVtYWlsIjoiYWRtaW5AbG9jYWxob3N0IiwiaW1hZ2VVcmwiOiJodHRwczovL3dwaW1nLndhbGxzdGNuLmNvbS9mNzc4NzM4Yy1lNGY4LTQ4NzAtYjYzNC01NjcwM2I0YWNhZmUuZ2lmP2ltYWdlVmlldzIvMS93LzgwL2gvODAiLCJhY3RpdmF0ZWQiOjEsImxhbmdLZXkiOiJlbiIsImFjdGl2YXRpb25LZXkiOm51bGwsInJlc2V0S2V5IjpudWxsLCJjcmVhdGVkQnkiOiJzeXN0ZW0iLCJjcmVhdGVkRGF0ZSI6bnVsbCwicmVzZXREYXRlIjpudWxsLCJsYXN0TW9kaWZpZWRCeSI6InN5c3RlbSIsImxhc3RNb2RpZmllZERhdGUiOm51bGx9LCJhdXRob3JpdGllcyI6WyJST0xFX0FETUlOIiwiUk9MRV9VU0VSIl0sImlhdCI6MTU0ODM5OTQzNCwiZXhwIjoxNTQ5Njk1NDM0fQ.9y9YOKtJaT33T56A2mKKrSeI0ojCmUFPU5JxvLNR3ds
    Cache-Control: no-cache
    Postman-Token: 0697e795-506d-fb51-f35a-cf6009437a8d
    
    

    Response:

    {
        "id": 3,
        "login": "admin",
        "firstName": "Administrator",
        "lastName": "Administrator",
        "email": "admin@localhost",
        "imageUrl": "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif?imageView2/1/w/80/h/80",
        "activated": 1,
        "langKey": "en",
        "activationKey": null,
        "resetKey": null,
        "createdBy": "system",
        "createdDate": null,
        "resetDate": null,
        "lastModifiedBy": "system",
        "lastModifiedDate": null,
        "authorities": [
            "ROLE_ADMIN",
            "ROLE_USER"
        ]
    }
    
  • Api access control and data filtering

    API prefixes control whether an interface is exposed to external access. /config/RouterSecurityConfiguration.ts

    export enum RouterSecurityType {
      PERMIT = 'permit',
      AUTHENTICATED = 'authenticated',
      REJECT = 'reject'
    }
    
    export default {
      '/api': RouterSecurityType.AUTHENTICATED,
      '/api/authenticate': RouterSecurityType.PERMIT
    }
    

    The Action method in the controller layer is shown below, which is annotated to control role permissions.

    decoded.allowRole refers to the permission of the role that allows the user to come in. Generally speaking, the user may have multiple roles, so when multiple permissions can be matched, allowRole only records the permission name at the top of the AuthorityCode array. /controller/RegionAction.ts

    /**
    * post
    * @param {Application.Context} context
    * @param decoded
    * @returns {Promise<void>}
    */
    @setRoute('/api/regions', RequestMethod.POST, [AuthorityCode.ROLE_ADMIN, AuthorityCode.ROLE_USER])
    async createRegion(context: Context, decoded?: DecodedUserInfo) {
        const regionRepository = getManager().getRepository(Region);
        let region: Region = regionRepository.create(<region>{
          ...context.request.body
        });
        if (decoded.allowRole === AuthorityCode.ROLE_USER) {
        Audit.addCreateInfo(region, decoded.user);
          region.isPublic = false;
          region.isDelete = false;
          region.isVisible = true;
        }
        const errors = await validate(region);
        if (errors.length > 0) {
          throw new BadRequestAlertException(null, errors);
        } else {
          await regionRepository.save(region);
          region = await regionRepository.findOne(region.id);
          await Elastic.syncCreate(region,regionRepository.metadata.tableName);
          context.body = region;
        }
    }
    /**
    * search
    * @param {Application.Context} context
    * @param decoded
    * @returns {Promise<void>}
    */
    @setRoute('/api/_search/regions', RequestMethod.GET, [AuthorityCode.ROLE_ADMIN, AuthorityCode.ROLE_USER])
    async searchArticleRegion(context: Context, decoded?: DecodedUserInfo) {
        let filter;
        if (decoded.allowRole === AuthorityCode.ROLE_USER) {
          filter = [
              {
                term: {
                  createUser: decoded.user.login
                }
              }
          ]
        }
        const res: any = await Elastic.search(getElasticSearchParams(context, filter), 'article_region');
        setElasticSearchPagingHeader(context, res);
        context.body = res.data;
    

Technology stack

License

MIT © snowfox

Package Sidebar

Install

npm i generator-magic-node

Weekly Downloads

0

Version

0.1.0-dev.27

License

MIT

Unpacked Size

116 kB

Total Files

46

Last publish

Collaborators

  • snow-fox