Skip to content

Commit

Permalink
$$$ update $$$
Browse files Browse the repository at this point in the history
  • Loading branch information
darekf77 committed Apr 29, 2024
1 parent bf1b943 commit a4b26d0
Show file tree
Hide file tree
Showing 27 changed files with 1,004 additions and 508 deletions.
3 changes: 0 additions & 3 deletions projects/container-v4/isomorphic-lib-v4/app/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,6 @@ import { FiredevAdmin } from 'firedev-ui'; // <- this is to replace by firedev
import { Stor } from 'firedev-storage'; // <- this is to replace by firedev
import { AppModule } from './app/app.module';

// @ts-ignore
window['firedev'] = new FiredevAdmin(window['ENV']);

if (environment.production) {
enableProdMode();
}
Expand Down
2 changes: 2 additions & 0 deletions src/lib/base-classes/base-abstract-entity.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { Entity } from "firedev-typeorm/src";
import { Orm } from "../orm";
import { BaseEntity } from "./base-entity";

@Entity()
export abstract class BaseAbstractEntity extends BaseEntity {

//#region @websql
Expand Down
9 changes: 9 additions & 0 deletions src/lib/base-classes/base-class.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,15 @@ import { inject } from '@angular/core';


export class BaseClass {

/**
* class initialization hook
* firedev after class instace creation
*/
_() {

}

/**
* Current endpoint context
*/
Expand Down
10 changes: 6 additions & 4 deletions src/lib/base-classes/base-controller.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import { FiredevController } from '../decorators/classes/controller-decorator';
import { EndpointContext } from "../endpoint-context";
import { Symbols } from "../symbols";
import { BaseClass } from "./base-class";


@FiredevController({ className: 'BaseController' })
export class BaseController extends BaseClass {

/**
* @deprecated
* init example data for db
*/
async initExampleDbData() {

initExampleDbData(): Promise<any> {
return void 0;
}
}

246 changes: 242 additions & 4 deletions src/lib/base-classes/base-crud-controller.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,249 @@
import { EndpointContext } from "../endpoint-context";
//#region imports
import { Symbols } from "../symbols";
import { BaseController } from "./base-controller";
import { BaseRepository } from "./base-repository";
import { GET, PUT, DELETE, POST, HEAD, PATCH } from '../decorators/http/http-methods-decorators';
import { Query, Path, Body } from '../decorators/http/http-params-decorators';
import { MySqlQuerySource } from 'firedev-type-sql/src';
import { Models } from '../models';
import { Helpers, _ } from 'tnp-core/src';
import { FiredevController, FiredevControllerOptions } from '../decorators/classes/controller-decorator';
import { ClassHelpers } from "../helpers/class-helpers";
import { Entity } from "firedev-typeorm/lib";
import { Validators } from "../validators";
import { FiredevEntityOptions } from "../decorators/classes/entity-decorator";
//#endregion


/**
* Please override property entityClassFn with entity class.
*/
@FiredevController({ className: 'BaseCrudController' })
export class BaseCrudController<Entity> extends BaseController {
constructor(__entity: Function) {
super();

//#region fields
crud?: BaseRepository<Entity> = this.inject(BaseRepository<Entity>);
dbQuery?: MySqlQuerySource;
/**
* Please provide entity as class propery entityClassFn:
*/
public entityClassFn: typeof Entity;
//#endregion

//#region init
async _() {
const configController = Reflect.getMetadata(Symbols.metadata.options.controller, ClassHelpers.getClassFnFromObject(this)) as FiredevControllerOptions;

const entityClassFn = this.entityClassFn || configController?.entity;
if (entityClassFn) {
const configEntity = Reflect.getMetadata(Symbols.metadata.options.entity, ClassHelpers.getClassFnFromObject(this)) as FiredevEntityOptions;
if (configEntity?.createTable === false) {
Helpers.warn(`Table for entity ${ClassHelpers.getName(entityClassFn)} will not be created. Crud will not work properly.`);
}
this.crud.entityClassFn = entityClassFn as any;
const connection = this.__endpoint_context__.connection;
this.dbQuery = new MySqlQuerySource(connection);
} else {
Helpers.error(`Entity class not provided for controller ${ClassHelpers.getName(this)}.
Please provide entity as class propery entityClassFn:
class ${ClassHelpers.getName(this)} extends BaseCrudController<Entity> {
// ...
entityClassFn = MyEntityClass;
// ...
}
`);
}

}
//#endregion

//#region bufferd changes
@GET(`/${Symbols.old.CRUD_TABLE_MODEL}/:id/property/:property`)
bufforedChanges(
@Path(`id`) id: number | string,
@Path(`property`) property: string,
@Query('alreadyLength') alreadyLength?: number
): Models.Http.Response<string | any[]> {
//#region @websqlFunc
return async (request, response) => {

const model = await this.crud.repo.findOne({
where: { id } as any
})
if (model === void 0) {
return;
}
Validators.preventUndefinedModel(model, id)
let value = model[property];
let result: any;
if (_.isString(value) || _.isArray(value)) {
result = (value as string).slice(alreadyLength);
}

return result;
}
//#endregion
}
//#endregion

//#region pagintation
@GET(`/${Symbols.old.CRUD_TABLE_MODELS}-pagination`)
pagination(
@Query('pageNumber') pageNumber: number = 1,
@Query('pageSize') pageSize: number = 10,
@Query('search') search: string = '',
): Models.Http.Response<Entity[]> {
//#region @websqlFunc
return async (request, response) => {
if (this.crud.repository) {

const query = {
page: pageNumber,
take: pageSize,
keyword: search,
};
// console.log({
// query
// })

const take = query.take || 10
const page = query.page || 1;
const skip = (page - 1) * take;
const keyword = query.keyword || ''

const [result, total] = await this.crud.repo.findAndCount(
{
// where: { name: Like('%' + keyword + '%') },
// order: { name: "DESC" },
take: take,
skip: skip
}
);


response?.setHeader(Symbols.old.X_TOTAL_COUNT, total)
// const lastPage = Math.ceil(total / take);
// const nextPage = page + 1 > lastPage ? null : page + 1;
// const prevPage = page - 1 < 1 ? null : page - 1;

// console.log({
// result,
// total
// })

return result as Entity[];
}
return []
}
//#endregion
}
//#endregion

//#region get all
@GET(`/${Symbols.old.CRUD_TABLE_MODELS}`)
getAll(): Models.Http.Response<Entity[]> {
//#region @websqlFunc
return async (request, response) => {
if (this.crud.repository) {
const { models, totalCount } = await this.crud.getAll();
response?.setHeader(Symbols.old.X_TOTAL_COUNT, totalCount)
return models;
}
return [];
}
//#endregion
}
//#endregion

//#region get by id
@GET(`/${Symbols.old.CRUD_TABLE_MODEL}/:id`)
getBy(@Path(`id`) id: number | string): Models.Http.Response<Entity> {
//#region @websqlFunc
return async () => {
const { model } = await this.crud.getBy(id);
return model;
}
//#endregion
}
//#endregion

//#region update by id
@PUT(`/${Symbols.old.CRUD_TABLE_MODEL}/:id`)
updateById(@Path(`id`) id: number | string, @Body() item: Entity): Models.Http.Response<Entity> {
//#region @websqlFunc

return async () => {
const { model } = await this.crud.updateById(id, item as any);
return model;

}
//#endregion
}
//#endregion

//#region bulk update
@PUT(`/bulk/${Symbols.old.CRUD_TABLE_MODELS}`)
bulkUpdate(@Body() items: Entity[]): Models.Http.Response<Entity[]> {
//#region @websqlFunc
return async () => {
if (!Array.isArray(items) || (items?.length === 0)) {
return [];
}
const { models } = await this.crud.bulkUpdate(items);
return models;
}
//#endregion
}
//#endregion

//#region delete by id
@DELETE(`/${Symbols.old.CRUD_TABLE_MODEL}/:id`)
deleteById(@Path(`id`) id: number): Models.Http.Response<Entity> {
//#region @websqlFunc
return async () => {
const { model } = await this.crud.deleteById(id);
return model;
}
//#endregion
}
//#endregion

//#region bulk delete
@DELETE(`/bulk/${Symbols.old.CRUD_TABLE_MODELS}/:ids`)
bulkDelete(@Path(`ids`) ids: (number | string)[]): Models.Http.Response<(number | string | Entity)[]> {
//#region @websqlFunc
return async () => {
const { models } = await this.crud.bulkDelete(ids);
return models;
}
//#endregion
}
//#endregion

//#region create
@POST(`/${Symbols.old.CRUD_TABLE_MODEL}/`)
create(@Body() item: Entity): Models.Http.Response<Entity> {
//#region @websqlFunc
return async () => {
const { model } = await this.crud.create(item as any);
return model as Entity;
}
//#endregion
}
//#endregion

//#region bulk create
@POST(`/bulk/${Symbols.old.CRUD_TABLE_MODELS}/`)
bulkCreate(@Body() items: Entity): Models.Http.Response<Entity[]> {
//#region @websqlFunc
return async () => {
const { models } = await this.crud.bulkCreate(items as any);
return models as Entity[];
}
//#endregion
}
//#endregion

}
3 changes: 2 additions & 1 deletion src/lib/base-classes/base-entity.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { Entity } from "firedev-typeorm/src";
import { EndpointContext } from "../endpoint-context";
import { Symbols } from "../symbols";
import { BaseClass } from "./base-class";


@Entity()
export class BaseEntity extends BaseClass {

}
Loading

0 comments on commit a4b26d0

Please sign in to comment.