Use-Case
Standard pattern to be used to maintain the code scalability by providing middleware-based flow. Each function can have its own middlewares for pre- and post-processing.
According to the pattern above all of the case-functions runs only basic rdbms operations, like getting data or writing data. And it's all based on the data structure. The middlewares are used to for additional actions.
How It's Done
The use-case is divided into at least 2 parts:
- Case (
case.go), where thecasefunctions (the main functions) are stored - Tycovar (
tycovar.go), where package scoped types, const, and variables are stored
Optionally, there can be other parts, such as:
- Helper (
helper.go), where internal functions are stored - Middleware (
middleware.go), where the pre- and post-processing functions are stored
Then proceed the following steps (example):
-
Inside the
tycovar.go, define the middleware types for each case functions. Make sure to:- Include dto, table definition, and transaction for the parameters since the middlewares are to utilize or modifies one ot the parameters.
- Make all of the parameter pointer for easier handling.
- Return
errorfor blocking purpose when error occurs.
type createMw func(input *e.Createdto, tx *gorm.DB) error . . -
Inside the
tycovar.go, create variables in form of array to make it possible to have more than one middleware. There are 2 modes (pre- and post-processing) for each case functions:var createPreMw []createMw var createPostMw []createMw . . -
Inside the
middleware.go, create the necessary middlewaresfunc createPreMwAddNamePrefix(input *e.Createdto, tx *gorm.DB) error { input.Name = "Prefix_" + input.Name return nil } -
Inside the
middleware.go, append the middlewares during initialization. The order of the does not really is important, except there are steps that are dependent on each other.func init() { createPreMw = append(createPreMw, createPreMwAddNamePrefix) } -
Loop through the middleware variables and call each middleware. Since there are 2 modes (pre- and post-processing), the order of the calls is important.