2.0.1-rc.5 • Published 2 years ago

chyz v2.0.1-rc.5

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

Hızlı şekilde microservis hazırlama için geliştirmeye başladım

Temel olarak yii2 php framework'ten örnekler alındı

Temel olarak basit bir Controller geliştirildi, ayrıca authentication geliştirildi.

Klasör Yapısı ---Controllers ---Models *---Log index.ts

`##Başlangıç yarn start

index.ts alanlar düzenlenmeli.

import {BaseChyz} from "../index";

require('dotenv-flow').config();
import Chyz ,{  DbConnection, BaseChyz} from "chyz/dist/";
import {AuthManager} from "chyz/dist/rbac/AuthManager"
import {WebUser} from "chyz/dist/web/WebUser";
import {User as Identity} from "./Models/User";


let config = {
    port: process.env.PORT || 8870,
    controllerpath: "Examples\\Controllers",
    components: {
        authManager: {
            class: AuthManager,
        },
        db: {
            class: DbConnection,
            database: process.env.DBDATABASE,
            username: process.env.DBUSER,
            password: process.env.DBPASS,
            options: {
                host: process.env.DBHOST,
                dialect: 'postgres',  /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */
                // disable logging; default: console.log
                logging: (msg: any) => BaseChyz.debug(msg)
            }
        },
        user: {
            'class': WebUser,
            'identityClass': User
        }
    }

}
Chyz.app(config).then((server)=>server.Start());

##Controller Basit şekilde kontroller oluşturulabilir.

/*
 *
 * Copyright (c) 2021-2021.. Chy Bilgisayar Bilisim
 * Author: Cihan Ozturk
 *  E-mail: cihan@chy.com.tr
 *  Github:https://github.com/cihan53/
 *
 */

import {AccessControl, BaseChyz, JwtHttpBearerAuth, ModelManager, Request, Response,} from "chyz/dist";
import {ForbiddenHttpException, Model, NotFoundHttpException, ValidationHttpException} from "chyz/dist/base";

import Utils from 'chyz/dist/requiments/Utils';
import {controller, get, post} from "chyz/dist/decorator";
import {Controller} from "chyz/dist/base/Controller";
import * as Util from "util";
import {uid} from "uid";

import {User} from "../Models/User";
import {AuthManager} from "../Lib/AuthManager";
import {CategoriesClass} from "../Models/Categories";


const keygen = require('ssh-keygen');
const os = require('os');
const bcrypt = require('bcrypt');
const JsonWebToken = require("jsonwebtoken");
const {Op} = require("sequelize");


@controller("/api")
class ApiController extends Controller {

    public myCheck(token) {
        console.log("myyyyyyyyyyyyyyyyyyyyy")
    }

    public behaviors(): any[] {

        return [{
            'authenticator': {
                "class": JwtHttpBearerAuth,
                // "auth": this.myCheck
            },
            'access': {
                'class': AccessControl,
                'only': ['order/list' ],
                'rules': [

                    {
                        'allow': true,
                        'actions': ['order/list' ],
                        'roles': ['editor'],
                    }
                ]
            }
        }]
    }

    @get("/")
    Index(req: Request, res: Response) {

        BaseChyz.logs().info("Site Controller Burası", this.id)
        return res.json({message: "index sayfası"})
    }

    @post("orderCreate")
    async Login(req: Request, res: Response) {
        let data = req.body;
        data.Customer.status = "true";

        //Customer Model Create
        let customer = ModelManager.Customer.save();
        //Order Model Create
        let order = ModelManager.Order;


        let transaction
        try {
            // get transaction
            transaction = await BaseChyz.getComponent("db").transaction();
            customer.load(data, "Customer");//load customer data
            let cus: any = await customer.save({}, {transaction});

            if (!cus) {
                throw new ValidationHttpException(customer.errors);
            }

            data.Order.customer_id = cus.id;
            
            order.load(data, "Order");
            let res1 = await order.save({}, {transaction});
            if (!res1) {
                throw new ValidationHttpException(order.errors);
            }

            // commit
            await transaction.commit();

        } catch (e) {
            if (transaction) {
                await transaction.rollback();
                BaseChyz.warn("Rollback transaction")
            }

            if (e instanceof ValidationHttpException)
                throw new ValidationHttpException(e.message)
            else
                throw new ForbiddenHttpException(e.message)
        }
        return res.send("Post Controller")
    }


    @get("order/list")
    async listOrder(req: Request, res: Response) {
        const {Products}: { Products: ProductsClass } = ModelManager;
        let product = await Products.findAll( );
        return res.json(product)

    }

    @get("categories")
    async Categories(req: Request, res: Response) {
        let product = await ModelManager.Categories.findAll({
            include: [
                {
                    model: ModelManager.Products.model(),
                }
            ]
        });
        return res.json(product)

    }

    error(req: Request, res: Response) {
        BaseChyz.logs().info("Error Sayfası")
        return res.send("Post Controller")
    }
}

module.exports = ApiController

Create Model

Veritabanı işlemleri için model oluşturma, sequelize desteklidir.

Model adı "Class" şeklinde bitmeli.

Örnek = "ModelNameClass"

import {Model, DataTypes} from "chyz/base/Model";

export class CustomerCLass extends Model {
    public tableName() {
        return 'customer';
    }

    public attributes() {
        return {
            username: {
                type: DataTypes.STRING,
                allowNull: false,
                validate: {
                    notEmpty: true,
                    len: [4, 255],
                }
            },
            email: {
                type: DataTypes.STRING,
                validate: {
                    isEmail: true
                }
            },
            firstname: {
                type: DataTypes.STRING,
                allowNull: false
            },
            lastname: {
                type: DataTypes.STRING,
            },
        }
    }

}
 
export class ProductsClass extends Model {
    [x: string]: any;

    tableName() {
        return 'products';
    }

    attributes() {
        return {
            // Model attributes are defined here
            title: {
                type: DataTypes.STRING,
                allowNull: false
            },
            model_id: {
                type: DataTypes.INTEGER,
                allowNull: false
            },
            properties: {
                type: DataTypes.STRING,
                allowNull: false
            }

        }
    }

    relations(): Relation[] {
        return [
            {
                type: "hasOne",
                foreignKey: "id",
                sourceKey: "customer_id",
                model: Customer.model()
            }
        ]
    }
}

/**
 * 
 */
export class CategoriesClass extends Model {
    [x: string]: any;

    alias() {
        return "c"
    }

    tableName() {
        return 'categories';
    }
    attributes() {
        return {
            // Model attributes are defined here
            title: {
                type: DataTypes.STRING,
                allowNull: false
            },
            properties: {
                type: DataTypes.STRING,
                allowNull: false
            }

        }
    }
    relations(): Relation[] {
        return [
            {
                type: "belongsToMany",
                foreignKey: "category_id",
                sourceKey: "id",
                as: 'product',
                model: ModelManager.Products.model(),
                through: ModelManager.ProductToCategories.model()
            }
        ]
    }

}

 

Http POST ve GET verilerini model'e yükleme

/**
 * post data
 *  {
 *      "Customer":{
 *          "firstname":"cihan",
 *          "lastname":"ozturk"
 *          ....
 *      }
 *  }
 * @type {Customer}
 */
import {  ModelManager} from "chyz/dist";
import {Customer} from "./Customer";

//Customer Model Create
let customer: Customer = ModelManager.Customer;
customer.load(req.body, "Customer");//load customer data
let cus: any = await customer.save();

Transaction

Transaction oluşturma

    let transaction
    try {
        // get transaction
        transaction = await BaseChyz.getComponent("db").transaction();
        //Customer Model Create
        let customer: Customer = ModelManager.Customer;
        customer.load(data, "Customer");//load customer data
        let cus: any = await customer.save({}, {transaction});
        if (!cus) {
            throw new ValidationHttpException(customer.errors);
        }
    } catch (e) {
        if (transaction) {
            await transaction.rollback();
            BaseChyz.warn("Rollback transaction");
        }
        
    }

Yetkilendirme için kullanıcı modeli

/*
 * Copyright (c) 2021. Chy Bilgisayar Bilisim
 * Author: Cihan Ozturk
 * E-mail: cihan@chy.com.tr
 * Github:https://github.com/cihan53/
 */
import {IdentityInterface} from "chyz/web/IdentityInterface";
// @ts-ignore
import {DataTypes} from "chyz/base";
import {Model} from "chyz/base";
import BaseChyz from "chyz/BaseChyz";

const bcrypt = require('bcrypt');
const JsonWebToken = require("jsonwebtoken");

export class User extends Model implements IdentityInterface {
    public tableName() {
        return 'users';
    }
    findIdentity(id: number) {
        throw new Error("Method not implemented.");
    }

    getId(): number {
        throw new Error("Method not implemented.");
    }

    getAuthKey(): string {
        throw new Error("Method not implemented.");
    }

    validateAuthKey(authKey: string): boolean {
        throw new Error("Method not implemented.");
    }

    /**
     * Returns auth manager associated with the user component.
     *
     * By default this is the `authManager` application component.
     * You may override this method to return a different auth manager instance if needed.
     */
    protected getAuthManager() {
        return BaseChyz.getComponent("authManager");
    }

    /**
     * Returns the access checker used for checking access.
     * @return CheckAccessInterface
     */
    protected getAccessChecker() {
        return this.accessChecker !== null ? this.accessChecker : this.getAuthManager();
    }
    
    /**
     *
     * @param permissionName
     * @param params
     * @param allowCaching
     */
    public async can(permissionName, params: any[] = [], allowCaching: boolean = true) {
        let accessChecker;
        if ((accessChecker = this.getAccessChecker()) === null) {
            return false;
        }

        let access = await accessChecker.checkAccess(this.getId(), permissionName, params);
        this._access[permissionName] = access;
        if (allowCaching && Utils.isEmpty(params)) {

        }
        return access;
    }

    public attributes() {
        return {
            // Model attributes are defined here
            username: {
                type: DataTypes.STRING,
                allowNull: false
            },
            password: {
                type: DataTypes.STRING,
                allowNull: false
            },
            user_role: {
                type: DataTypes.STRING,
                allowNull: false
            },
            salt_text: {
                type: DataTypes.STRING
                // allowNull defaults to true
            }
        }
    }

    async findIdentityByAccessToken(token, type) {
        
        
        let decoded = JsonWebToken.decode(token, {complete: true})
        if (!decoded.payload.user) {
            return null;
        }
        let identity = await this.findOne({where: {id: parseInt(decoded.payload.user)}});
        if(identity){
            BaseChyz.debug("Find Identity By AccessToken: User Found", decoded.payload)
            try {
                JsonWebToken.verify(token, identity.salt_text);
                this.setIdentity(identity);
                BaseChyz.debug("Find Identity By AccessToken: User Verify Success")
                return this;
            } catch(err) {
                if (err.name == "TokenExpiredError")
                    BaseChyz.debug("Find Identity By AccessToken: Token Expired")
                else
                    BaseChyz.debug("Find Identity By AccessToken: User Verify Failed")
                return null;
            }
        }
        BaseChyz.debug("Find Identity By AccessToken: User Verify Failed")
        return null;
    }


}
2.0.0-rc.46

2 years ago

2.0.0-rc.44

2 years ago

2.0.0-rc.42

2 years ago

2.0.0-rc.43

2 years ago

2.0.0-rc.40

2 years ago

2.0.0-rc.41

2 years ago

2.0.0-rc.39

2 years ago

2.0.0-rc.37

2 years ago

2.0.0-rc.38

2 years ago

2.0.0-rc.36

2 years ago

2.0.1-rc.0

2 years ago

2.0.1-rc.1

2 years ago

2.0.1-rc.2

2 years ago

2.0.1-rc.3

2 years ago

2.0.1-rc.4

2 years ago

2.0.1-rc.5

2 years ago

2.0.0-rc.33

2 years ago

2.0.0-rc.34

2 years ago

2.0.0-rc.31

2 years ago

2.0.0-rc.32

2 years ago

2.0.0-rc.30

2 years ago

2.0.0-rc.29

2 years ago

2.0.0-rc.28

2 years ago

2.0.0-rc.26

2 years ago

2.0.0-rc.27

2 years ago

2.0.0-rc.24

2 years ago

2.0.0-rc.25

2 years ago

2.0.0-rc.22

2 years ago

2.0.0-rc.23

2 years ago

2.0.0-rc.20

2 years ago

2.0.0-rc.21

2 years ago

2.0.0-rc.19

2 years ago

2.0.0-rc.17

2 years ago

2.0.0-rc.18

2 years ago

2.0.0-rc.15

2 years ago

2.0.0-rc.16

2 years ago

2.0.0-rc.14

3 years ago

1.2.5-rc.3

3 years ago

1.2.5-rc.2

3 years ago

1.2.5-rc.0

3 years ago

2.0.0-rc.3

3 years ago

2.0.0-rc.4

3 years ago

2.0.0-rc.5

3 years ago

2.0.0-rc.13

3 years ago

2.0.0-rc.11

3 years ago

2.0.0-rc.12

3 years ago

2.0.0-rc.6

3 years ago

2.0.0-rc.7

3 years ago

2.0.0-rc.8

3 years ago

1.2.4-rc.1

3 years ago

1.2.4-rc.2

3 years ago

1.2.4-rc.3

3 years ago

1.2.4-rc.4

3 years ago

1.2.4-rc.5

3 years ago

1.2.4-rc.6

3 years ago

1.2.4-rc.7

3 years ago

1.1.1-rc.2

3 years ago

1.1.0-rc.2

3 years ago

1.1.0-rc.1

3 years ago

1.1.0-rc.0

3 years ago

1.2.1-rc.3

3 years ago

1.2.1-rc.2

3 years ago

1.2.1-rc.0

3 years ago

1.0.13-rc.26

3 years ago

1.0.13-rc.20

3 years ago

1.0.13-rc.21

3 years ago

1.0.13-rc.22

3 years ago

1.0.13-rc.23

3 years ago

1.0.13-rc.24

3 years ago

1.0.13-rc.25

3 years ago

1.0.13-rc.1

4 years ago

1.0.13-rc.2

4 years ago

1.0.13-rc.3

4 years ago

1.0.13-rc.4

4 years ago

1.0.13-rc.9

4 years ago

1.0.13-rc.5

4 years ago

1.0.13-rc.6

4 years ago

1.0.13-rc.7

4 years ago

1.0.13-rc.8

4 years ago

1.0.13-rc.10

4 years ago

1.0.13-rc.11

4 years ago

1.0.13-rc.12

4 years ago

1.0.13-rc.13

4 years ago

1.0.13-rc.14

4 years ago

1.0.13-rc.16

4 years ago

1.0.13-rc.17

4 years ago

1.0.13-rc.18

4 years ago

1.0.12-rc.28

4 years ago

1.0.13-rc.19

4 years ago

1.0.12-rc.29

4 years ago

1.0.12-rc.19

4 years ago

1.0.12-rc.17

4 years ago

1.0.12-rc.18

4 years ago

1.0.12-rc.24

4 years ago

1.0.12-rc.25

4 years ago

1.0.12-rc.22

4 years ago

1.0.12-rc.23

4 years ago

1.0.12-rc.20

4 years ago

1.0.12-rc.21

4 years ago

1.0.12-rc.26

4 years ago

1.0.12-rc.27

4 years ago

1.0.12-rc.15

4 years ago

1.0.12-rc.16

4 years ago

1.0.12-rc.14

4 years ago

1.0.12-rc.9

4 years ago

1.0.12-rc.13

4 years ago

1.0.12-rc.11

4 years ago

1.0.12-rc.12

4 years ago

1.0.12-rc.10

4 years ago

1.0.12-rc.5

4 years ago

1.0.12-rc.7

4 years ago

1.0.12-rc.6

4 years ago

1.0.12-rc.8

4 years ago

1.0.12-rc.3

4 years ago

1.0.12-rc.1

4 years ago

1.0.12-rc.2

4 years ago

1.0.11-rc.13

4 years ago

1.0.11-rc.14

4 years ago

1.0.11-rc.15

4 years ago

1.0.12-rc.0

4 years ago

1.0.11-rc.16

4 years ago

1.0.11-rc.17

4 years ago

1.0.11-rc.18

4 years ago

1.0.11-rc.19

4 years ago

1.0.11-rc.20

4 years ago

1.0.11-rc.10

4 years ago

1.0.11-rc.11

4 years ago

1.0.11-rc.9

4 years ago

1.0.11-rc.7

4 years ago

1.0.11-rc.8

4 years ago

1.0.11-rc.5

4 years ago

1.0.11-rc.6

4 years ago

1.0.11-rc.3

4 years ago

1.0.11-rc.4

4 years ago

1.0.11-rc.2

4 years ago

1.0.11

4 years ago

1.0.10

4 years ago

1.0.9

4 years ago

1.0.8

4 years ago

1.0.7

4 years ago

1.0.6

4 years ago

1.0.5

4 years ago

1.0.4

4 years ago

1.0.3

4 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago