models.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916
  1. package common
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "regexp"
  7. "strconv"
  8. "strings"
  9. "text/template"
  10. "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/api"
  11. "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/api/errs"
  12. ts "git.eugeniocarvalho.dev/eugeniucarvalho/gg/generators/typescript"
  13. "github.com/kataras/iris/v12/context"
  14. "go.mongodb.org/mongo-driver/bson/primitive"
  15. )
  16. const (
  17. BSON = "go.mongodb.org/mongo-driver/bson"
  18. BSONX = "go.mongodb.org/mongo-driver/x/bsonx"
  19. MONGO = "go.mongodb.org/mongo-driver/mongo"
  20. BSON_PRIMITIVE = "go.mongodb.org/mongo-driver/bson/primitive"
  21. IRIS_CTX = "github.com/kataras/iris/v12/context"
  22. IRIS = "github.com/kataras/iris/v12"
  23. UPDATE_RELATION = "UpdateRelation"
  24. BASE_HAS_DEPENDE = "HasDep"
  25. )
  26. var (
  27. API_URL = "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/api"
  28. API_ERROR = "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/api/errs"
  29. CODE_GEN_V2_COMMON = "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/common"
  30. CODE_GEN_V2_AUTHORIZATION = "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/authorization"
  31. // Variavel de controle de acesso aos models da API.
  32. Models = &api.Mongo{}
  33. camelToUnderRegex = regexp.MustCompile(`([^[:lower:]])`)
  34. //Generic e
  35. Generic = regexp.MustCompile("(?P<type>[\\w-_]+)<(?P<dtype>[\\w\\*]+)>")
  36. //GenericPart e
  37. GenericPart = regexp.MustCompile("<(?P<id>[\\w\\*]+)>")
  38. //ImportMap e
  39. importMap = map[string]string{
  40. "bson": BSON,
  41. "primitive": BSON_PRIMITIVE,
  42. }
  43. SR = SchemasRelations{
  44. R: map[string][]*Relation{},
  45. }
  46. )
  47. type BuildOptions struct {
  48. Mode string
  49. IgnoreBuildSteps string
  50. IgnoreBuildStepsValues map[int]bool
  51. }
  52. func (b *BuildOptions) IgnoreStep(step int) bool {
  53. _, ok := b.IgnoreBuildStepsValues[step]
  54. return ok
  55. }
  56. func (b *BuildOptions) Parse() error {
  57. var (
  58. value int
  59. err error
  60. )
  61. if b.IgnoreBuildStepsValues == nil {
  62. b.IgnoreBuildStepsValues = map[int]bool{}
  63. }
  64. for _, v := range strings.Split(b.IgnoreBuildSteps, ",") {
  65. if value, err = strconv.Atoi(v); err != nil {
  66. return err
  67. }
  68. b.IgnoreBuildStepsValues[value] = true
  69. }
  70. return nil
  71. }
  72. func ImportMap(base string) string {
  73. if v, ok := importMap[base]; ok {
  74. return v
  75. }
  76. panic(fmt.Sprintf("Import %s não definido", base))
  77. }
  78. type Project struct {
  79. OutPath string `json:"outPath"`
  80. Package string `json:"package"`
  81. Kind string `json:"kind"`
  82. Etag string `json:"etag"`
  83. Version string `json:"version"`
  84. BuildVersion string `json:"buildVersion"`
  85. ID string `json:"id"`
  86. Name string `json:"name"`
  87. DataBaseSufix string `json:"dataBaseSufix"`
  88. Mode string `json:"mode"`
  89. Revision string `json:"revision"`
  90. Title string `json:"title"`
  91. Description string `json:"description"`
  92. OwnerDomain string `json:"ownerDomain"`
  93. OwnerName string `json:"ownerName"`
  94. DocumentationLink string `json:"documentationLink"`
  95. Protocol string `json:"protocol"`
  96. BaseURL string `json:"baseUrl"`
  97. BasePath string `json:"basePath"`
  98. Middlewares []string `json:"middlewares"`
  99. ServicePath string `json:"servicePath"`
  100. GitRepository string `json:"git.repository"`
  101. Environment Environment `json:"environment"`
  102. Variables map[string]interface{} `json:"variables"`
  103. Resource *Resource `json:"-"`
  104. Schemas []*Entity `json:"schemas"`
  105. SchemasRef map[string]*Entity `json:"-"`
  106. Resources []*Resource `json:"resources"`
  107. Auth Auth `json:"auth"`
  108. TypeScriptSource *ts.File `json:"-"`
  109. Icons map[string]string `json:"icons"`
  110. ReplaceWhenEmpty map[string]bool `json:"ReplaceWhenEmpty"`
  111. OmitEmpty map[string]bool `json:"omitempty"`
  112. Clients []*Client `json:"clients,omitempty"`
  113. Translators map[string]TranslationFn `json:"-"`
  114. FormatMap map[string]string `json:"-"`
  115. Queries *QueryDef `json:"queries"`
  116. ACL *ACL `json:"acl"`
  117. Custom map[string]interface{} `json:"custom"`
  118. }
  119. type ACL struct {
  120. Roles []*Role `json:"roles"`
  121. Permissions []*Permission `json:"permissions"`
  122. }
  123. type QueryDef struct {
  124. Blacklistwords map[string][]string `json:"blacklistwords"`
  125. Queries map[string]string `json:"queries"`
  126. Common map[string]string `json:"common"`
  127. }
  128. type Role struct {
  129. Title string `json:"title"`
  130. Description string `json:"description"`
  131. ID string `json:"id"`
  132. AllowRemove bool `json:"allowRemove,omitempty"`
  133. Permissions []string `json:"permissions"`
  134. }
  135. type Permission struct {
  136. Title string `json:"title"`
  137. Description string `json:"description"`
  138. ID string `json:"id"`
  139. }
  140. type Client struct {
  141. Id string `json:"id,omitempty"`
  142. OutputDir string `json:"outputDir,omitempty"`
  143. }
  144. type Auth struct {
  145. AuthCookieDomain string `json:"authCookieDomain"`
  146. AuthTokenID string `json:"authTokenId"`
  147. Oauth2 Oauth2 `json:"oauth2"`
  148. }
  149. type Oauth2 struct {
  150. URI string `json:"uri"`
  151. Client Oauth2Client `json:"client"`
  152. Scopes []Scope `json:"scopes"`
  153. }
  154. type Oauth2Client struct {
  155. RedirectURI string `json:"redirect_uri"`
  156. ClientID string `json:"client_id"`
  157. ClientSecret string `json:"client_secret"`
  158. Scope []string `json:"scope"`
  159. }
  160. type Scope struct {
  161. ID string `json:"id"`
  162. PromptToUser []string `json:"promptToUser"`
  163. Description string `json:"description"`
  164. }
  165. type EnvironmentVariable struct {
  166. ID string `json:"id"`
  167. CamelID string `json:"-"`
  168. Default string `json:"default"`
  169. Required bool `json:"required,omitempty"`
  170. Description string `json:"description"`
  171. }
  172. type Environment map[string]*EnvironmentVariable
  173. type Entity struct {
  174. HasMode bool `json:"hasMode"`
  175. ID string `json:"id"`
  176. Type string `json:"type"`
  177. Description string `json:"description"`
  178. Collection string `json:"collection"`
  179. DB string `json:"db"`
  180. Extends []string `json:"extends"`
  181. Properties []*Propertie `json:"properties"`
  182. Representations map[string][]string `json:"representations"`
  183. Custom map[string]interface{} `json:"custom"`
  184. }
  185. type Resource struct {
  186. ID string `json:"id"`
  187. Description string `json:"description"`
  188. Entity string `json:"entity"`
  189. Formats []*Value `json:"formats"`
  190. Methods []*Method `json:"methods"`
  191. CommonParams map[string]*Parameter `json:"commonParams"`
  192. Custom map[string]interface{} `json:"custom"`
  193. }
  194. type Method struct {
  195. ID string `json:"id"`
  196. Entity string `json:"entity"`
  197. Type string `json:"type"` // Assume valores {one, list, implement}
  198. Path string `json:"path"`
  199. Template string `json:"template"`
  200. BeforePersistAction bool `json:"beforePersistAction"`
  201. HttpMethod string `json:"httpMethod"`
  202. Description string `json:"description"`
  203. Response string `json:"response"`
  204. Request string `json:"request"`
  205. Scopes []string `json:"scopes"`
  206. Middlewares []string `json:"middlewares"`
  207. Postresponse []string `json:"postresponse"`
  208. ParameterOrder []string `json:"parameterOrder"`
  209. ParametersString []string `json:"parameters"`
  210. Resource *Resource `json:"-"`
  211. Hooks map[string]bool `json:"hooks"`
  212. Parameters map[string]*Parameter `json:"parametersmap"`
  213. Preconditions []Action `json:"preconditions"`
  214. BeforeResponse []Action `json:"beforeResponse"`
  215. Custom map[string]interface{} `json:"custom"`
  216. // Parameters map[string]*Parameter `json:"parameters"`
  217. }
  218. type Action struct {
  219. ID string `json:"id"`
  220. Context map[string]interface{} `json:"context"`
  221. }
  222. type Parameter struct {
  223. ID string `json:"id"`
  224. Type string `json:"type"`
  225. Required bool `json:"required"`
  226. Description string `json:"description"`
  227. Default string `json:"default"`
  228. Location string `json:"location"`
  229. ConvertTo string `json:"convertTo"`
  230. Custom map[string]interface{} `json:"custom"`
  231. // Validation *ValidationRule `json:"validation"`
  232. Validation map[string]interface{} `json:"validation"`
  233. }
  234. // type ValidationRule struct {
  235. // Accept []*Value `json:"-"`
  236. // AcceptRef []string `json:"accept"`
  237. // Reject []*Value `json:"reject"`
  238. // RejectRef []string `json:"-"`
  239. // In []string `json:"in"`
  240. // Contains string `json:"contains"`
  241. // Regex string `json:"regex"`
  242. // Min string `json:"min"`
  243. // Max string `json:"max"`
  244. // Type string `json:"type"`
  245. // }
  246. type Value struct {
  247. Id string `json:"id"`
  248. Value string `json:"value"`
  249. Default bool `json:"default"`
  250. Fields string `json:"fields"`
  251. Description string `json:"description"`
  252. }
  253. type Propertie struct {
  254. ID string `json:"id"`
  255. Name string `json:"name"`
  256. Type string `json:"type"`
  257. Description string `json:"description"`
  258. AutogenerateInput string `json:"autogenerate"`
  259. Autogenerate map[string]AutoGenDef `json:"-"`
  260. Targets string `json:"targets"`
  261. Array bool `json:"array"`
  262. Relation bool `json:"relation"`
  263. TagVisited bool `json:"-"`
  264. Reference bool `json:"reference"`
  265. Readonly bool `json:"readonly"`
  266. Unique bool `json:"uniq"`
  267. Default interface{} `json:"default"`
  268. Enum []string `json:"enum"`
  269. Values []interface{} `json:"values"`
  270. EnumDescriptions []string `json:"enumDescriptions"`
  271. Tags map[string]string `json:"tags"`
  272. Filter []*Filter `json:"filter"`
  273. Custom map[string]interface{} `json:"custom"`
  274. }
  275. type AutoGenDef struct {
  276. Type string
  277. Args []string
  278. }
  279. type Filter struct {
  280. Path string `json:"path"`
  281. Type string `json:"type"`
  282. Label string `json:"label"`
  283. UserEnumAsOptions bool `json:"userEnumAsOptions"`
  284. Multiples bool `json:"multiples"`
  285. Options []FilterOption `json:"options,omitempty"`
  286. }
  287. type FilterOption struct {
  288. Value interface{} `json:"value"`
  289. Label string `json:"label"`
  290. }
  291. type ApiFilter struct {
  292. Id string `json:"id"`
  293. Date int64 `json:"date"`
  294. Fields []*Filter `json:"fields"`
  295. }
  296. func NewApiFilter(id string) *ApiFilter {
  297. return &ApiFilter{
  298. Id: id,
  299. Fields: []*Filter{},
  300. }
  301. }
  302. func RequestParams(args string, params map[string]*Parameter) func(ctx context.Context) (resp interface{}, err *errs.Error) {
  303. argsList := strings.Split(args, ",")
  304. return func(ctx context.Context) (resp interface{}, err *errs.Error) {
  305. var (
  306. values = ctx.Values()
  307. id string
  308. value interface{}
  309. sourceValue interface{}
  310. param *Parameter
  311. paramsMap = map[string]interface{}{}
  312. )
  313. values.Set("$params", paramsMap)
  314. for _, arg := range argsList {
  315. param = params[arg]
  316. switch param.Location {
  317. case "query":
  318. id = "q." + arg
  319. value = api.Q(ctx, arg, param.Default)
  320. case "path":
  321. id = "p." + arg
  322. value = api.P(ctx, arg, param.Default)
  323. }
  324. sourceValue = value
  325. emptyValue := (value == "" || value == nil)
  326. if param.Required && emptyValue {
  327. invalidArgument := errs.InvalidArgument()
  328. invalidArgument.Message = fmt.Sprintf(
  329. "ParamRequired: param '%s' in '%s'",
  330. param.ID,
  331. param.Location,
  332. )
  333. return nil, invalidArgument
  334. }
  335. if !emptyValue && param.ConvertTo != "" {
  336. if value, err = convertValueByType(param.ConvertTo, value); err != nil {
  337. invalidArgument := errs.InvalidArgument()
  338. invalidArgument.Message = fmt.Sprintf(
  339. "ParamTypeConversionError: param '%s' in '%s' with value '%v'. Waiting a %s ",
  340. param.ID,
  341. param.Location,
  342. value,
  343. param.ConvertTo,
  344. )
  345. return nil, invalidArgument
  346. }
  347. }
  348. if param.Validation != nil {
  349. for validator, args := range param.Validation {
  350. if fn, found := validationParamFunctions[validator]; found {
  351. ctx.Application().Logger().Info(fmt.Sprintf("validadete[%s][%s][%v]", validator, args, value))
  352. if err = fn(param, value, args); err != nil {
  353. return nil, err
  354. }
  355. }
  356. }
  357. }
  358. values.Set(id, value)
  359. paramsMap[fmt.Sprintf("%s_conv", arg)] = value
  360. paramsMap[arg] = sourceValue
  361. }
  362. ctx.Next()
  363. return
  364. }
  365. }
  366. var (
  367. convertionTypeFunctions = map[string]func(interface{}) (interface{}, *errs.Error){
  368. "ObjectID": stringToObjectId,
  369. "bool": stringToBool,
  370. "int": stringToInt,
  371. "number": stringToFloat,
  372. }
  373. validationParamFunctions = map[string]func(*Parameter,interface{}, interface{}) *errs.Error{
  374. "min": func(param *Parameter, value interface{}, minString interface{}) *errs.Error {
  375. var input float64
  376. if v, ok := value.(int64); ok {
  377. input = float64(v)
  378. } else if v, ok := value.(float64); ok {
  379. input = v
  380. } else if v, ok := value.(string); ok {
  381. input = float64(len(v))
  382. } else {
  383. invalidArgument := errs.InvalidArgument()
  384. invalidArgument.Message = fmt.Sprintf(
  385. "[%s] ValueRestriction: mim validation requires (int,float,string)",
  386. param.ID,
  387. )
  388. return invalidArgument
  389. }
  390. if min, convert := minString.(float64); !convert || input < min {
  391. invalidArgument := errs.InvalidArgument()
  392. invalidArgument.Message = fmt.Sprintf(
  393. "[%s] ValueRestriction: value > %v. Received (%v)",
  394. param.ID,
  395. minString,
  396. value,
  397. )
  398. return invalidArgument
  399. }
  400. return nil
  401. },
  402. "max": func(param *Parameter, value interface{}, maxString interface{}) *errs.Error {
  403. var input float64
  404. if v, ok := value.(int64); ok {
  405. input = float64(v)
  406. } else if v, ok := value.(float64); ok {
  407. input = v
  408. } else if v, ok := value.(string); ok {
  409. input = float64(len(v))
  410. } else {
  411. invalidArgument := errs.InvalidArgument()
  412. invalidArgument.Message = fmt.Sprintf(
  413. "[%s] ValueRestriction: mim validation requires (int,float,string)",
  414. param.ID,
  415. )
  416. return invalidArgument
  417. }
  418. if max, convert := maxString.(float64); !convert || input > max {
  419. invalidArgument := errs.InvalidArgument()
  420. invalidArgument.Message = fmt.Sprintf(
  421. "[%s] ValueRestriction: value < %v. Received (%v)",
  422. param.ID,
  423. maxString,
  424. value,
  425. )
  426. return invalidArgument
  427. }
  428. return nil
  429. },
  430. "accept": func(param *Parameter, input interface{}, accept interface{}) *errs.Error {
  431. var (
  432. acceptValues = accept.([]interface{})
  433. acceptValuesString = []string{}
  434. value = fmt.Sprintf("%v", input)
  435. )
  436. for _, acceptValue := range acceptValues {
  437. if value == acceptValue.(string) {
  438. return nil
  439. }
  440. acceptValuesString = append(acceptValuesString, acceptValue.(string))
  441. }
  442. invalidArgument := errs.InvalidArgument()
  443. invalidArgument.Message = fmt.Sprintf(
  444. "[%s] ValueRestriction: '%s' isn't accept. Accept [%s]",
  445. param.ID,
  446. value,
  447. strings.Join(acceptValuesString, ","),
  448. )
  449. return invalidArgument
  450. },
  451. "reject": func(param *Parameter, input interface{}, reject interface{}) *errs.Error {
  452. var (
  453. rejectValues = reject.([]interface{})
  454. value = fmt.Sprintf("%v", input)
  455. )
  456. for _, rejectValue := range rejectValues {
  457. if value == rejectValue.(string) {
  458. invalidArgument := errs.InvalidArgument()
  459. invalidArgument.Message = fmt.Sprintf(
  460. "[%s] ValueRestriction: '%s' isn't accept",
  461. param.ID,
  462. value,
  463. )
  464. return invalidArgument
  465. }
  466. }
  467. return nil
  468. },
  469. "regex": func(param *Parameter, input interface{}, regex interface{}) *errs.Error {
  470. var (
  471. regexString = regex.(string)
  472. value = input.(string)
  473. )
  474. regexInstance := regexp.MustCompile(regexString)
  475. if !regexInstance.Match([]byte(value)) {
  476. invalidArgument := errs.InvalidArgument()
  477. invalidArgument.Message = fmt.Sprintf(
  478. "[%s] ValueRestriction: '%s' isn't accept",
  479. param.ID,
  480. value,
  481. )
  482. return invalidArgument
  483. }
  484. return nil
  485. },
  486. }
  487. )
  488. func stringToObjectId(value interface{}) (interface{}, *errs.Error) {
  489. var (
  490. valueString = value.(string)
  491. valueObjectID primitive.ObjectID
  492. err error
  493. )
  494. if valueObjectID, err = primitive.ObjectIDFromHex(valueString); err != nil {
  495. invalidArgument := errs.InvalidArgument()
  496. invalidArgument.Message = fmt.Sprintf("The value '%s' is'nt a valid ObjectId", valueString)
  497. return nil, invalidArgument
  498. }
  499. return valueObjectID, nil
  500. }
  501. func stringToBool(value interface{}) (interface{}, *errs.Error) {
  502. var (
  503. valueBool bool
  504. err error
  505. )
  506. if valueBool, err = strconv.ParseBool(value.(string)); err != nil {
  507. invalidArgument := errs.InvalidArgument()
  508. invalidArgument.Message = fmt.Sprintf("The value '%s' is'nt a valid boolean. Accept [true,1,T,false,0,F]", valueBool)
  509. return nil, invalidArgument
  510. }
  511. return valueBool, nil
  512. }
  513. func stringToInt(value interface{}) (interface{}, *errs.Error) {
  514. var (
  515. valueInt int64
  516. err error
  517. )
  518. if valueInt, err = strconv.ParseInt(value.(string), 10, 64); err != nil {
  519. invalidArgument := errs.InvalidArgument()
  520. invalidArgument.Message = fmt.Sprintf("The value '%s' is'nt a valid int", valueInt)
  521. return nil, invalidArgument
  522. }
  523. return valueInt, nil
  524. }
  525. func stringToFloat(value interface{}) (interface{}, *errs.Error) {
  526. var (
  527. valueFloat float64
  528. err error
  529. )
  530. if valueFloat, err = strconv.ParseFloat(value.(string), 64); err != nil {
  531. invalidArgument := errs.InvalidArgument()
  532. invalidArgument.Message = fmt.Sprintf("The value '%s' is'nt a valid number", valueFloat)
  533. return nil, invalidArgument
  534. }
  535. return valueFloat, nil
  536. }
  537. func convertValueByType(typ string, value interface{}) (interface{}, *errs.Error) {
  538. var err *errs.Error
  539. if fn, found := convertionTypeFunctions[typ]; found {
  540. if value, err = fn(value); err != nil {
  541. return nil, err
  542. }
  543. }
  544. return value, nil
  545. }
  546. // func validateParam(param *Parameter, value interface{}) (interface{}, *errs.Error) {
  547. // var err *errs.Error
  548. // return value, nil
  549. // }
  550. func (t *Method) Hook(id string) bool {
  551. // active := t.Hooks[id]
  552. // return active
  553. return t.Hooks[id]
  554. }
  555. func (t *Propertie) ParseAutogenerate() error {
  556. if t.AutogenerateInput != "" {
  557. parts := strings.Split(t.AutogenerateInput, ":")
  558. if len(parts) < 2 {
  559. return fmt.Errorf("Invalid autogenerate input '%s' in attribute '%s'.", t.AutogenerateInput, t.ID)
  560. }
  561. if t.Autogenerate == nil {
  562. t.Autogenerate = map[string]AutoGenDef{}
  563. }
  564. args := strings.Split(parts[1], "#")
  565. for _, k := range strings.Split(parts[0], ",") {
  566. t.Autogenerate[k] = AutoGenDef{
  567. Type: args[0],
  568. Args: args[1:],
  569. }
  570. }
  571. }
  572. return nil
  573. }
  574. type SchemasRelations struct {
  575. R map[string][]*Relation
  576. }
  577. type Relation struct {
  578. Source string
  579. Target string
  580. Attr string
  581. Collection string
  582. DB string
  583. IsArray bool
  584. }
  585. type EntityInfo struct {
  586. Name string
  587. Origin string
  588. NewName string
  589. DynamicType string
  590. DynamicTypeId string
  591. IsGeneric bool
  592. }
  593. type TranslationFn func(p *Project) error
  594. func (p *Project) Build(b *BuildOptions) error {
  595. var err error
  596. for _, c := range p.Clients {
  597. if fn, found := p.Translators[c.Id]; found {
  598. if err = fn(p); err != nil {
  599. fmt.Println("error on ", c.Id)
  600. return err
  601. }
  602. } else {
  603. return fmt.Errorf("Middleware '%s' not defined!", c.Id)
  604. }
  605. }
  606. // fmt.Println("--- RunBuildCommads")
  607. return RunBuildCommads(p, b)
  608. }
  609. func (p *Project) OutDirectory(path string) {
  610. p.OutPath = path
  611. }
  612. func (p *Project) Client(id string) *Client {
  613. for _, c := range p.Clients {
  614. if c.Id == id {
  615. return c
  616. }
  617. }
  618. return nil
  619. }
  620. func (p *Project) Save(path string) error {
  621. data, err := json.MarshalIndent(p, "", " ")
  622. if err == nil {
  623. err = FilePutContentsBytes(path, data, 0777)
  624. }
  625. return err
  626. }
  627. func (p *Project) GetCollection(entity string) string {
  628. for _, e := range p.Schemas {
  629. if e.ID == entity {
  630. return e.Collection
  631. }
  632. }
  633. return "undefined"
  634. }
  635. func (p *Project) GetEntityDB(entity string) string {
  636. if en, found := p.SchemasRef[entity]; found {
  637. return en.DB + p.DataBaseSufix
  638. }
  639. panic(fmt.Sprintf("DB attribute is empty in entity '%s'", entity))
  640. }
  641. func (p *Project) EntityDesc(ID string) *Entity {
  642. if _, y := p.SchemasRef[ID]; !y {
  643. fmt.Println("EntityDesc(ID)", ID)
  644. return nil
  645. }
  646. return p.SchemasRef[ID]
  647. }
  648. func (m *Method) HasPathParams() bool {
  649. return len(m.ParameterOrder) > 0
  650. }
  651. func (m *Method) HasFormatParam() (bool, *Parameter) {
  652. for id, param := range m.Parameters {
  653. // param = m.Parameters[id]
  654. // fmt.Println("param:", param.ID)
  655. if id == "format" {
  656. return true, param
  657. }
  658. }
  659. return false, nil
  660. }
  661. func (p *Project) GetUrlFromMethod(method *Method) string {
  662. return p.BaseURL + method.Path
  663. }
  664. func (p *Project) ResponseEntity(property string) *EntityInfo {
  665. var (
  666. pi = &EntityInfo{
  667. Origin: property,
  668. }
  669. )
  670. match := Generic.FindStringSubmatch(property)
  671. if len(match) == 0 {
  672. return pi
  673. }
  674. for i, name := range Generic.SubexpNames() {
  675. switch name {
  676. case "type":
  677. pi.Name = match[i]
  678. case "dtype":
  679. pi.DynamicType = match[i]
  680. pi.IsGeneric = true
  681. }
  682. }
  683. if pi.IsGeneric {
  684. entity := p.GetSchema(pi.Name)
  685. match = GenericPart.FindStringSubmatch(entity.ID)
  686. for i, name := range GenericPart.SubexpNames() {
  687. switch name {
  688. case "id":
  689. pi.DynamicTypeId = match[i]
  690. }
  691. }
  692. }
  693. pi.NewName = pi.Name + UpFirst(strings.Replace(pi.DynamicType, "*", "", -1))
  694. return pi
  695. }
  696. func (p *Project) GetPath(m *Method) string {
  697. path := []byte(p.BasePath + m.Path)
  698. for attr, param := range m.Parameters {
  699. path = regexp.MustCompile("{"+attr+"}").ReplaceAll(path, []byte("{"+attr+":"+param.Type+"}"))
  700. }
  701. return string(path)
  702. }
  703. func (p *Project) GetSchema(id string) *Entity {
  704. id = strings.Replace(id, "*", "", -1)
  705. if model, ok := p.SchemasRef[id]; ok {
  706. return model
  707. }
  708. panic(fmt.Sprintf("Entity '%s' not defined!", id))
  709. }
  710. // Metodos das propriedades
  711. func (p *Propertie) FillTags(project *Project, propName string) {
  712. if p.TagVisited {
  713. return
  714. }
  715. if propName == "Id" {
  716. }
  717. if p.Tags != nil {
  718. for k, v := range p.Tags {
  719. if _, found := project.ReplaceWhenEmpty[k]; found && v == "" {
  720. p.Tags[k] = LcFirst(p.ID)
  721. }
  722. if _, found := project.OmitEmpty[k]; found {
  723. if p.Tags[k] != "-" {
  724. p.Tags[k] += ",omitempty"
  725. }
  726. }
  727. }
  728. }
  729. p.TagVisited = true
  730. }
  731. func (p *Propertie) GetType() string {
  732. return strings.Replace(p.Type, "*", "", 1)
  733. }
  734. // Metodos das informacoes da entidade
  735. func (p *EntityInfo) TranslateType(typ string) string {
  736. if typ == p.DynamicTypeId {
  737. return p.DynamicType
  738. }
  739. return typ
  740. }
  741. // Metodos do esquema de relacoes
  742. // Add adiciona uma relação ao esquema
  743. func (s *SchemasRelations) Has(entity string) bool {
  744. // spew.Dump(s)
  745. _, found := s.R[entity]
  746. return found
  747. }
  748. // Add adiciona uma relação ao esquema
  749. func (s *SchemasRelations) Get(entity string) []*Relation {
  750. if e, found := s.R[entity]; found {
  751. return e
  752. }
  753. return []*Relation{}
  754. }
  755. // Add adiciona uma relação ao esquema
  756. func (s *SchemasRelations) Add(r *Relation) {
  757. if _, found := s.R[r.Source]; !found {
  758. s.R[r.Source] = []*Relation{}
  759. }
  760. s.R[r.Source] = append(s.R[r.Source], r)
  761. }
  762. func ParseTemplate(input string, name ...string) (*template.Template, error) {
  763. var tmpl, err = template.New(strings.Join(name, "")).Parse(input)
  764. return tmpl, err
  765. }
  766. func TemplateToString(template *template.Template, data interface{}) (string, error) {
  767. var result bytes.Buffer
  768. if err := template.Execute(&result, data); err != nil {
  769. return "", err
  770. }
  771. return result.String(), nil
  772. }
  773. func NewProject() *Project {
  774. return &Project{
  775. Mode: "",
  776. SchemasRef: map[string]*Entity{},
  777. Icons: map[string]string{},
  778. ReplaceWhenEmpty: map[string]bool{},
  779. OmitEmpty: map[string]bool{},
  780. FormatMap: map[string]string{},
  781. Queries: &QueryDef{},
  782. Schemas: []*Entity{},
  783. Resources: []*Resource{},
  784. Translators: map[string]TranslationFn{},
  785. }
  786. }