model

package module
v0.0.70 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 22, 2023 License: MIT Imports: 4 Imported by: 40

README

Estructuras que utilizo con frecuencia en proyectos escritos en Go

ejemplo de uso en un objeto

func MedicalHistory() model.Object {
	return model.Object{
		Name:           "medicalhistory",
		PrincipalFieldsName: []string{"service_name"},
		Fields: []model.Field{
			{Name: "id_medicalhistory", Legend: "id", Input: unixid.InputPK()},
			{Name: "id_patient", Legend: "paciente", Input: unixid.InputPK()},

			{Name: "staff_id", Legend: "Id", Input: unixid.InputPK()},
			{Name: "staff_name", Legend: "Atendido por", Input: input.Text()},
			{Name: "staff_ocupation", Legend: "Especialidad", Input: input.Text()},
			{Name: "staff_area", Legend: "Area", Input: input.Check(Area{})},

			{Name: "service_id", Legend: "Prestación", Input: unixid.InputPK()},

			{Name: "day_attention", Legend: "Dia Atención", Input: input.Date()},
			{Name: "hour_attention", Legend: "Hora", Input: input.Hour(`min="08:15"`, `max="20:15"`)},

			{Name: "reason", Legend: "Motivo Consulta, Servicio o Procedimiento", Input: input.TextArea()},
			{Name: "diagnostic", Legend: "Diagnostico (Descripción)", Input: input.TextArea()},
			{Name: "prescription", Legend: "Prescripción (Conclusion)", Input: input.TextArea()},

			{Name: "last_print_file", Legend: "Ultima Impresión en Archivo", Input: input.Text()},
		},
	}
}

Documentation

Index

Constants

View Source
const INPUT_PATTERN = `input\.(\w+)\([^)]*\)`
View Source
const PREFIX_ID_NAME = "id_"

Variables

This section is empty.

Functions

func Error added in v0.0.40

func Error(messages ...any) err

only support: error, int, int64, string, map[string]interface{}

func GetFieldNamesFrom added in v0.0.68

func GetFieldNamesFrom(struct_in interface{}) ([]string, error)

Types

type AfterClicked added in v0.0.52

type AfterClicked interface {
	// data del objeto que fue cliqueado por el usuario
	UserClicked(data map[string]string)
}

type AfterCreate added in v0.0.46

type AfterCreate interface {
	SetObjectInDomAfterCreate(data ...map[string]string) error
}

type AfterDelete added in v0.0.46

type AfterDelete interface {
	SetObjectInDomAfterDelete(data ...map[string]string) error
}

type AfterRead added in v0.0.49

type AfterRead interface {
	SetObjectInDomAfterRead(data ...map[string]string) error
}

type AfterUpdate added in v0.0.46

type AfterUpdate interface {
	SetObjectInDomAfterUpdate(data ...map[string]string) error
}

type AlternativeValidateAdapter added in v0.0.69

type AlternativeValidateAdapter interface {
	ValidateData(its_new, its_update_or_delete bool, all_data ...map[string]string) error
}

type AppInfo added in v0.0.67

type AppInfo struct {
	App_name         string
	App_version      string
	Business_name    string
	Business_address string
	Business_phone   string
}

type AuthAdapter added in v0.0.58

type AuthAdapter interface {
	UserAuthNumber
	LoginUser
}

type BackendHandler added in v0.0.46

type BackendHandler struct {
	BootResponse

	CreateApi
	ReadApi
	UpdateApi
	DeleteApi
}

type BootActions added in v0.0.44

type BootActions struct {
	JsonBootActions string
	JsonBootTests   string
}

type BootResponse added in v0.0.45

type BootResponse interface {
	AddBootResponse(u *User) ([]Response, error)
}

type ContainerViewAdapter added in v0.0.70

type ContainerViewAdapter interface {
	BuildContainerView(id, field_name string, allow_skip_completed bool) string
}

todo el contenido html por defecto del objeto

type CreateApi added in v0.0.31

type CreateApi interface {
	Create(u *User, data ...map[string]string) error
}

type CutData added in v0.0.19

type CutData struct {

	// ej Modelo Objeto: usuario := Object{Name: "Usuario",Fields: []Field{
	// 		{Name: "name"}, //0
	// 		{Name: "email"},//1
	// 		{Name: "phone"},//2
	// 	},}
	// ej data normal con todos los campos: {"name":"John Doe","email":"johndoe@example.com","phone":"555"}
	// version recortada Data: {"John Doe","johndoe@example.com","555"}
	// Index Objeto al codificar = {"0:0","1:1","2:2"}
	// ej no mail: {"marcel", "777"}
	// Index al codificar = {"0:0","1:2"}
	Index map[int8]int8 `json:"i"`
	//Data ej en mapa: "Data":[{"id":"222","name":"manzana","valor":"1200"}]
	// ahora: "Data":["222","manzana","1200"]
	Data []string `json:"d"`
}

type CutResponse added in v0.0.19

type CutResponse struct {
	//Action,Object,Module,Message
	//ej: ["create","user","ModuleUsers","ok"]
	CutOptions []string  `json:"o"`
	CutData    []CutData `json:"d"`
}

func (*CutResponse) CutResponseDecode added in v0.0.21

func (cr *CutResponse) CutResponseDecode(data []map[string]string) (out Response)

type DataBaseAdapter added in v0.0.35

type DataBaseAdapter interface {
	IdHandler
	RunOnClientDB() bool //verdadero corren en el cliente ej browser. por defecto falso corre en el servidor
	// items support in server db: []map[string]string, map[string]string
	CreateObjectsInDB(table_name string, backup_required bool, items any) error

	// from_tables ej: "users,products" or: public.reservation, public.patient"
	// params: map[string]string ej:{
	// LIMIT: 10, 5, 100. note: Postgres y MySQL: "LIMIT 10", SQLite: "LIMIT 10 OFFSET 0" OR "" no limit
	// ORDER_BY: name,phone,address
	// SELECT: "name, phone, address" default *
	// WHERE: "patient.id_patient = reservation.id_patient AND reservation.id_staff = '2'"
	// ARGS: "1,4,33"
	// }
	ReadObjectsInDB(from_tables string, params ...map[string]string) ([]map[string]string, error)
	//params: callback fun ej: fun([]map[string]string,error)
	// "ORDER_BY": "patient_name", "SORT":"DESC" DEFAULT "ASC"
	ReadStringDataAsyncInDB(r ReadDBParams, callback func([]map[string]string, error))
	ReadAnyDataAsyncInDB(r ReadDBParams, callback func([]map[string]interface{}, error))

	UpdateObjectsInDB(table_name string, data ...map[string]string) error
	DeleteObjectsInDB(table_name string, data ...map[string]string) error

	CreateTablesInDB(objects []*Object, result func(error))

	BackupDataBase(callback func(error))
}

type DataConverter added in v0.0.68

type DataConverter interface {
	//map_in ej []map[string]string or map[string]string
	EncodeMaps(map_in any, object_name ...string) (out []byte, err error)
	DecodeMaps(in []byte, object_name ...string) (out []map[string]string, err error)

	EncodeResponses(requests ...Response) ([]byte, error)
	DecodeResponses(data []byte) ([]Response, error)
}

si nombre del objeto no se ingresa se codifica a json de forma normal

type DeleteApi added in v0.0.31

type DeleteApi interface {
	Delete(u *User, data ...map[string]string) ([]map[string]string, error)
}

type DomAdapter added in v0.0.47

type DomAdapter interface {
	InnerHTML(html_content string, o *Object)
	InsertAfterBegin(html_content string, o *Object)
	InsertBeforeEnd(html_content string, o *Object)
	// querySelector ej: "a[name='xxx']"
	ElementClicking(querySelector string) error

	CallFunction(functionName string, args ...any)
	//esperar en milliseconds ej: 500, 2000 ..
	WaitFor(milliseconds int, callback func())
}

type FetchAdapter added in v0.0.68

type FetchAdapter interface {
	//method ej: GET,POST
	// endpoint ej: http://localhost/upload
	// object ej: imagen
	// body_rq any ej: []map[string]string, map[string]string
	SendOneRequest(method, endpoint, object string, body_rq any, response func([]map[string]string, error))
	// only POST method
	SendAllRequests(endpoint string, body_rq []Response, response func([]Response, error))
}

type Field

type Field struct {
	// si el campo comienza com id_ se considera como único y perteneciente a una tabla específica ej: id_user su tabla es user
	// otros ej: id_usuario, apellido, address, city etc
	Name          string
	Legend        string //como se mostrara al usuario el campo en el encabezado ej: "name" por "Nombre Usuario"
	SourceTable   string // tabla origen ej: patient,user,product
	NotRenderHtml bool   // si no se necesita en formulario html

	*Input

	SkipCompletionAllowed bool //se permite que el campo no este completado. por defecto siempre sera requerido

	Unique          bool //campo único e inalterable en db
	NotRequiredInDB bool // campo no requerido en base de datos al crear tabla
	Encrypted       bool // si estará encriptado su almacenamiento o no
}

func (Field) IsPrimaryKey added in v0.0.35

func (f Field) IsPrimaryKey(o *Object) bool

type FileApi added in v0.0.33

type FileApi interface {
	// FileAddUploadApi(h *Handlers, source *Object, file_settings any) error
	//backend file_request ej: r *http.Request, w http.ResponseWriter
	//frontend file_request ej: blob file js.Value
	FileUpload(object_name, area_file string, file_request ...any) (out []map[string]string, err error)
	//params ej: id:123
	FilePath(params map[string]string) (file_path, area string, err error)
}

type FileDiskRW added in v0.0.68

type FileDiskRW interface {
	FileGet(path string) (any, error)

	FileDelete(path string) error
}

type FormAdapter added in v0.0.66

type FormAdapter interface {
	FormReset(o *Object) error
	FormAutoFill(o *Object) error
	FormComplete(o *Object, data map[string]string) error
}

type Handlers added in v0.0.60

type Handlers struct {
	ProductionMode bool
	FileRootFolder string // default "app_files"
	AppInfo
	AuthAdapter

	ThemeAdapter
	DataBaseAdapter
	TimeAdapter

	DomAdapter
	FormAdapter
	HtmlAdapter

	FetchAdapter
	DataConverter

	FileApi
	FileDiskRW

	MessageAdapter
	Logger

	Test *Tests
	// contains filtered or unexported fields
}

func (*Handlers) AddModules added in v0.0.68

func (h *Handlers) AddModules(new_modules ...*Module)

func (*Handlers) AddObjects added in v0.0.68

func (h *Handlers) AddObjects(new_objects ...*Object)

func (Handlers) CheckInterfaces added in v0.0.68

func (h Handlers) CheckInterfaces(pkg_name string, struct_in interface{}) error

func (Handlers) GetModuleByName added in v0.0.68

func (h Handlers) GetModuleByName(module_name string) (*Module, error)

func (Handlers) GetModules added in v0.0.68

func (h Handlers) GetModules() []*Module

func (Handlers) GetObjectByName added in v0.0.68

func (h Handlers) GetObjectByName(object_name string) (*Object, error)

func (Handlers) GetObjects added in v0.0.68

func (h Handlers) GetObjects() []*Object

type HtmlAdapter added in v0.0.70

type HtmlAdapter interface {
	// retorna un elemento html del tipo js.Value
	GetHtmlModule(module_name string) (jsValue any, err error)
}

type Icon added in v0.0.28

type Icon struct {
	Id      string   //ej: icon-search, icon-btn-save, icon-btn-new
	ViewBox string   //ej: "0 0 16 16", "0 0 448 512"
	Paths   []string //ej: m11.51 11..,m7.051..,m3.267 15...
}

type IdHandler added in v0.0.56

type IdHandler interface {
	GetNewID() string
}

type Input added in v0.0.5

type Input struct {
	InputName string

	Minimum int
	Maximum int

	Tag
	ItemViewAdapter
	ResetViewAdapter
	Validate

	TestData
}

type ItemViewAdapter added in v0.0.70

type ItemViewAdapter interface {
	BuildItemsView(all_data ...map[string]string) (html string)
}

type Logger added in v0.0.60

type Logger interface {
	// retorno una interfaz solo para simplificar funciones de tipo syscall/js
	Log(message ...any) interface{}
}

type LoginUser added in v0.0.68

type LoginUser interface {
	// params ej: r *http
	GetLoginUser(params any) (*User, error)
}

type MessageAdapter added in v0.0.69

type MessageAdapter interface {
	UserMessage(message ...any) interface{}
}

type Module

type Module struct {
	//nombre modulo ej: chat,patient,user
	ModuleName string
	//Titulo que vera el usuario ej: "Modulo Fotografía"
	Title string
	// id icono para utilizar en sprite svg ej: icon-info
	IconID string

	//interfaz usuario modulo
	UI

	// ej:	`<div class="target-module">
	// 	<select name="select">
	// 		<option value="value1">Value 1</option>
	// 		<option value="value2" selected>Value 2</option>
	// 	</select>
	// </div>`
	HeaderInputTarget string

	//areas soportadas por el modulo ej: 'a','t','x'
	Areas []byte
	// objetos o componentes que contiene el modulo ej: patient,user,datalist,search....
	Objects []*Object

	// tipo de entradas usadas en el modulo
	Inputs []*Input

	*Handlers

	Tests []Response
}

func (*Module) AddInputs added in v0.0.56

func (m *Module) AddInputs(new_inputs []*Input, from string) error

from ej: file, user

type ModuleHandler added in v0.0.68

type ModuleHandler interface {
	GetModules() []*Module
	GetModuleByName(module_name string) (*Module, error)
}

type NotifyBootData added in v0.0.50

type NotifyBootData interface {
	NotifyBootDataIsLoaded()
}

type Object

type Object struct {
	// ej: module.client, client.search_footer,user.datalist
	ObjectName string
	Table      string //tabla origen db ej: users

	PrincipalFieldsName []string //campos mas representativos ej: name, address, phone
	NoAddObjectInDB     bool
	Fields              []Field //campos

	*Module // módulo origen

	BackHandler BackendHandler

	FrontHandler FrontendHandler

	PrinterHandler

	FormData map[string]string // data temporal formulario

	AlternativeValidateAdapter
}

func (Object) CallJsFunctionObject added in v0.0.70

func (o Object) CallJsFunctionObject(func_name string, enable bool, params ...map[string]interface{})

func (Object) ClickElement added in v0.0.70

func (o Object) ClickElement(query_element string) error

func (Object) ClickModule added in v0.0.70

func (o Object) ClickModule() error

func (Object) ClickingID added in v0.0.70

func (o Object) ClickingID(id string) error

func (Object) Columns

func (o Object) Columns() (columns []string)

func (Object) DataDecode added in v0.0.19

func (o Object) DataDecode(cut_data ...CutData) ([]map[string]string, error)

func (Object) DataEncode added in v0.0.19

func (o Object) DataEncode(all_data ...map[string]string) ([]CutData, error)

DataEncode quita los nombres de los campos de la data según modelo del objeto

func (Object) FieldExist added in v0.0.16

func (o Object) FieldExist(field_name string) (Field, bool)

func (Object) FieldsToFormValidate added in v0.0.66

func (o Object) FieldsToFormValidate() (fiels_out []Field)

func (Object) FilterRemoveFields

func (o Object) FilterRemoveFields(namesToRemove ...string) (fiels_out []Field)

func (Object) GetFieldsByNames added in v0.0.50

func (o Object) GetFieldsByNames(required_names ...string) ([]Field, error)

func (Object) GetID

func (o Object) GetID(data_search map[string]string) string

func (Object) GetRepresentativeTextField

func (o Object) GetRepresentativeTextField(data_element map[string]string) (values string)

func (Object) GetTablesNames added in v0.0.50

func (o Object) GetTablesNames() (out []string)

func (Object) JoinFieldNames added in v0.0.48

func (o Object) JoinFieldNames(add_prefix_table_name bool) (out string)

ej: id_patient,patient_name,patient_run - add_prefix_table_name: true = patient.id_patient,patient.patient_name,patient.patient_run

func (Object) MainName

func (o Object) MainName() string

func (Object) OnlyRequiredDbFieldsThisObject added in v0.0.63

func (o Object) OnlyRequiredDbFieldsThisObject() (db_field []Field)

solo campos requeridos en la base de datos. NOTA: puntero []*Field no funciona con slice

func (Object) PrimaryKeyName

func (o Object) PrimaryKeyName(options ...string) string

ej: "id_client", options: "add_prefix_table_name" = "client.id_client"

func (Object) RenderFields

func (o Object) RenderFields() (fiels_out []Field)

func (Object) RequiredFields

func (o Object) RequiredFields() (fiels_out []Field)

func (Object) Response added in v0.0.35

func (o Object) Response(data []map[string]string, options ...string) Response

options ej: update,delete,"mensaje a enviar" default action: create

func (Object) TestData added in v0.0.39

func (o Object) TestData(required_objects int, skip_id, wrong_data bool) ([]map[string]string, error)

func (Object) ValidateData added in v0.0.16

func (o Object) ValidateData(its_new, its_update_or_delete bool, all_data ...map[string]string) error

validar data objeto

func (Object) Where added in v0.0.50

func (o Object) Where(data map[string]string) (out string)

ej: reservation.id_patient = patient.id_patient AND reservation.id_staff = '1635574887' AND reservation.reservation_day = '29'

type ObjectsHandler added in v0.0.68

type ObjectsHandler interface {
	AddObjects(o ...*Object)
	GetObjects() []*Object
	GetObjectByName(object_name string) (*Object, error)
}

type Package added in v0.0.35

type Package struct {
	SkipMeInResponse bool     `json:"-"` //  saltarme al difundir
	Recipients       []string `json:"-"` // lista de ip, token o ids según app para el reenvió al finalizar solicitud
	TargetArea       bool     `json:"-"` // si es falso el destino por defecto es publico de lo contrario sera para todos quines tengan la misma area del usuario solicitante
	Response
}

type Page added in v0.0.33

type Page struct {
	StyleSheet string // url ej style.css

	AppName    string
	AppVersion string

	SpriteIcons string

	Menu string

	UserName string
	UserArea string
	Message  string

	Modules string

	Script string // ej main.js

	// JsonBootActions string //index ej <meta name="JsonBootActions" content="{{.JsonBootActions}}">
	// JsonBootTests   string
	BootActions
}

index.html ej: {{.StyleSheet}} {{.AppName}} {{.AppVersion}} {{.SpriteIcons}} {{.Menu}} {{.Message}} {{.UserName}} {{.UserArea}} {{.Modules}} {{.Script}} {{.Data}}

type Permission

type Permission struct {
	Read  bool
	Write bool
}

type PrinterHandler added in v0.0.66

type PrinterHandler interface {
	PrintFormObject()
}

type ReadApi added in v0.0.31

type ReadApi interface {
	Read(u *User, data ...map[string]string) ([]map[string]string, error)
}

type ReadDBParams added in v0.0.66

type ReadDBParams struct {
	FROM_TABLE      string
	ID              string   // unique search
	WHERE           []string //
	SEARCH_ARGUMENT string
	ORDER_BY        string
	SORT_DESC       bool //default ASC
}

type ReadData added in v0.0.69

type ReadData interface {
	ReadByID(id string) ([]map[string]string, error)
}

type Request

type Request struct {
	//usuario que ejecuta la solicitud
	*User
	// paquetes de solicitud y respuesta
	Packages []Package
}

type ResetViewAdapter added in v0.0.70

type ResetViewAdapter interface {
	ResetAdapterView()
}

type ResetViewObjectAdapter added in v0.0.70

type ResetViewObjectAdapter interface {
	ResetObjectView()
}

type Response

type Response struct {
	Action  string              `json:"a,omitempty"` //acción a realizar con la solicitud: create, read, update, delete o error
	Object  string              `json:"o,omitempty"` //nombre de la tabla u objeto controlador hacia donde va la solicitud
	Message string              `json:"g,omitempty"` //mensaje para el usuario de la solicitud
	Data    []map[string]string `json:"d,omitempty"` //data entrada y respuesta json
}

type SourceData added in v0.0.44

type SourceData interface {
	SourceData() map[string]string
}

type Tag added in v0.0.26

type Tag interface {
	HtmlName() string
	ContainerViewAdapter
}

type TestData added in v0.0.10

type TestData interface {
	GoodTestData() (out []string)
	WrongTestData() (out []string)
}

type Tests added in v0.0.70

type Tests struct {
	*Object
	NameObject string `Legend:"Nombre Objeto"`

	ClickingID   string `Legend:"Click en Objeto"` // ej Click
	ClickModule  string `Legend:"Click en Modulo"`
	ClickElement string `Legend:"Click en Elemento html"` // ej: "button[name='btn_cancel']"

	Wait string `Legend:"Espera en milisegundos"` // ej 200
	// contains filtered or unexported fields
}

func (*Tests) RunModuleTests added in v0.0.70

func (a *Tests) RunModuleTests(all_tests ...Response) (err string)

type ThemeAdapter added in v0.0.47

type ThemeAdapter interface {
	// MenuButtonTemplate ej: <li class="navbar-item"><a href="#` + module_name + `" tabindex="` + index + `" class="navbar-link" name="` + module_name + `">
	// <svg aria-hidden="true" focusable="false" class="fa-primary"><use xlink:href="#` + icon_id + `" /></svg>
	// <span class="link-text">` + title + `</span></a></li>
	MenuButtonTemplate(module_name, index, icon_id, title string) string
	MenuClassName() string // ej: .menu-container
	MenuItemClass() string // ej: navbar-item

	ModuleClassName() string //ej: slider_panel

	ModuleTemplate(m *Module, form *Object, list ContainerViewAdapter) string

	FunctionMessageName() string // ej: ShowMessageToUser
	// ej query: "div#"+o.ModuleName+" [data-id='"+o.ObjectName+"']"
	QuerySelectorMenuModule(module_name string) string
	QuerySelectorModule(module_name string) string
	QuerySelectorObject(module_name, object_name string) string
}

type TimeAdapter added in v0.0.47

type TimeAdapter interface {
	TimeNow
	TimeWeek
	UnixTimeHandler
}

type TimeNow added in v0.0.52

type TimeNow interface {
	// layout ej: 2006-01-02
	ToDay(layout string) string
}

type TimeWeek added in v0.0.52

type TimeWeek interface {
	//date ej: 2006-01-02,  0 para Domingo, 1 para Lunes, etc.
	WeekDayNumber(date_in string) (int, error)
}

type UI added in v0.0.26

type UI interface {
	UserInterface(options ...string) string
}

type UnixTimeHandler added in v0.0.56

type UnixTimeHandler interface {
	UnixNano() int64
}

ej: time.Now()

type UpdateApi added in v0.0.31

type UpdateApi interface {
	Update(u *User, data ...map[string]string) error
}

type User

type User struct {
	Token          string // token de sesión solicitante
	Id             string // id usuario
	Ip             string
	Name           string
	Area           string //0 sin area.. un que byte y uint8 son lo mismo en go la idea que aca sea un valor de carácter ej: a,s,p...
	AccessLevel    string // aquí valor numérico 0 a 255
	LastConnection string //time.Time

}

type UserAuthNumber added in v0.0.51

type UserAuthNumber interface {
	UserAuthNumber() (string, error)
}

ej: 1 or 2 or 34 or 400.....

type Validate added in v0.0.5

type Validate interface {
	//options html ej: data-option="ch_doc"
	ValidateField(data_in string, skip_validation bool, options ...string) error
}

type ViewAdapter added in v0.0.70

type ViewAdapter interface {
	NameViewAdapter() string
	ContainerViewAdapter
	ItemViewAdapter
	ResetViewAdapter
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL