details.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. const _ = require('lodash')
  2. const app = require('../../app')
  3. const details = ({
  4. typeName,
  5. typePlural,
  6. camelName,
  7. camelPlural,
  8. paramName,
  9. paramPlural,
  10. apiPrefix,
  11. appPrefix,
  12. columns
  13. }) => {
  14. const defaultInput = column => html`
  15. <md-input-container>
  16. <label>${column.fieldName}</label>
  17. <input type="${column.type || 'text'}" ng-model="model.${raw(column.camelName)}" />
  18. </md-input-container>
  19. `
  20. app.component(`app${typeName}DetailsPage`, {
  21. template: html`
  22. <app-user-area>
  23. <h1>${typeName}</h1>
  24. <form name="form" ng-submit="ctrl.submit()">
  25. ${columns.map(c => c.input || defaultInput(c))}
  26. <div>
  27. <md-button type="submit">Submit</md-button>
  28. </div>
  29. </form>
  30. </app-user-area>
  31. `,
  32. controllerAs: 'ctrl',
  33. controller: function(api, $scope, $routeParams, $mdToast) {
  34. const crud = api.crud(apiPrefix)
  35. let original
  36. if ($routeParams.id === 'new') {
  37. original = {}
  38. $scope.model = Object.create(original)
  39. } else {
  40. crud.read($routeParams.id).then(model => {
  41. original = model
  42. $scope.model = Object.create(original)
  43. })
  44. }
  45. this.submit = async () => {
  46. try {
  47. if ($routeParams.id === 'new') {
  48. await crud.create($scope.model)
  49. } else {
  50. const obj = {}
  51. for (var key in $scope.model) {
  52. if ($scope.model.hasOwnProperty(key)) {
  53. obj[key] = $scope.model[key]
  54. }
  55. }
  56. await crud.update(original.id, obj)
  57. }
  58. $mdToast.showSimple(`${typeName} saved.`)
  59. } catch (err) {
  60. console.error(err)
  61. $mdToast.showSimple(`Could not save ${typeName}: ${err.message || err}`)
  62. }
  63. }
  64. }
  65. })
  66. }
  67. module.exports = details