Programing

AngularJS : REST 리소스에 매핑되는 객체 생성 (ORM 스타일)

lottogame 2020. 11. 21. 08:21
반응형

AngularJS : REST 리소스에 매핑되는 객체 생성 (ORM 스타일)


저는 AngularJS를 처음 접했지만 서버의 REST Api 백엔드에 연결하는 방법을 잘 모르겠습니다.

예를 들어 GET-ing으로 얻은 "이미지"리소스가 있다고 가정합니다. myApi / image / 1 /. 이것은 다양한 필드가있는 json 객체를 반환합니다. 다음과 같이 말하겠습니다.

{url: "some/url", date_created: 1235845}

이제 AngularJS 앱에서이 "Image"객체를 표현하고 싶습니다. 이 표현은 단순한 필드 매핑 그 이상입니다. 예를 들어 date_create필드를 사람이 읽을 수있는 것으로 변환하는 함수와 같은 "도우미"함수를 추가하고 싶습니다 .

$ resource 서비스에 대해 알고 있지만 Angular에서 Resource를 사용하여 JSON 개체를 가져 오지만 다양한 도우미 함수를 추가하여 향상시키는 기본 "클래스"를 만드는 데 필요한 작업이 무엇인지 잘 모르겠습니다.

보너스 포인트 :

또한 모델간에 "관계"를 추가하는 방법도 명확하지 않습니다. 예를 들어 내부에 "이미지"리소스가 포함 된 "사용자"리소스가있을 수 있으며 사용자 리소스를 가져 오지만의 "이미지"부분에서 "이미지"도우미 함수를 호출 할 수 있습니다. 모델.


JSData
각도 데이터로 시작된 프로젝트는 이제 "사용하기 쉽고 안심할 수 있도록 구축 된 프레임 워크에 구애받지 않는 데이터 저장소"입니다. 그것은 훌륭한 문서를 가지고 있으며 관계, 다중 백엔드 (http, localStorage, firebase), 유효성 검사 및 물론 각도 통합을 지원합니다.
http://www.js-data.io/

BreezeJS AngularJS와 YouTube 채널이 기능 사용하여 비디오 BreezeJS을

클라이언트 측 필터링 및 기타 멋진 기능을 지원하는 고급 ORM입니다. OData 를 지원하는 백엔드에 가장 적합 하지만 다른 유형의 백엔드에서 작동하도록 만들 수 있습니다.

ngResource
또 다른 옵션은 사용하는 것입니다 ngResource를 , 여기에 자신의 기능을 확장하는 방법에 대한 예입니다 :

module.factory('Task', function ($resource) {
    var Task = $resource(WEBROOT + 'api/tasks/:id', {id: '@id'}, {update: { method: 'PUT'}});
    angular.extend(Task.prototype, {

        anExampleMethod: function () {
            return 4;
        },

        /**
         * Backbone-style save() that inserts or updated the record based on the presence of an id.
         */
        save: function (values) {
            if (values) {
                angular.extend(this, values);
            }
            if (this.id) {
                return this.$update();
            }
            return this.$save();
        }
    });
    return Task;
});

ngResource Backbone.Model에 비해 매우 제한적이라는 것을 알았습니다 .

  • Model.parse를 통한 사용자 지정 JSON 구문 분석
  • BaseModel 확장 가능 (ngResource에 baseUrl 없음)
  • Backbone.sync와 같은 다른 후크는 LocalStorage 등을 활성화합니다.

Restangular
"Rest API Restful 리소스를 적절하고 쉽게 처리하기위한 AngularJS 서비스"
http://ngmodules.org/modules/restangular

또는 다른 ORM의 클라이언트 측 JavaScript ORM에 사용할 수있는 옵션 중 일부를 사용해보십시오
.


저는 Restangular의 제작자이므로 제 의견이 편향 될 수 있습니다.

그러나 Bob이 말했듯이 Restangular를 사용할 수 있습니다.

Restangular는 Restful API 리소스를 사용하여 트리를 살펴 봅니다. 여기에 새 메소드를 추가 할 수도 있습니다.

다음은 코딩 예제입니다 : https://github.com/mgonto/restangular#lets-code

그리고 이렇게하면 객체에 새로운 메소드를 추가 할 수 있습니다 (보너스 포인트 :)) https://github.com/mgonto/restangular#creating-new-restangular-methods

이것이 당신을 위해 잘되기를 바랍니다 :).

그렇지 않으면 ngResource ($ resource)를 사용할 수도 있지만 제 생각에는 "love"와 "sugar"가 필요합니다.

베스트


간단한 상호 작용을 위해 Angular-Resource ( http://docs.angularjs.org/api/ngResource . $ resource)를 사용할 수 있습니다. 이것은 간단한 REST 상호 작용에 매우 유용 할 수 있습니다 (다운로드하려면 http : //code.angularjs. org / 1.0.6 / )

안타깝게도 angular 리소스를 사용할 때만 제한적으로 제어 할 수 있으며 더 고급 기능을 사용하려면 Angularjs $ http 서비스 ( http://docs.angularjs.org/api/ng . $ http)를 기반으로 자체 서비스를 만들어야합니다 .

도움이되기를 바랍니다.


많은 연구 끝에 사용 가능한 모든 솔루션의 포괄적 인 목록은 다음과 같습니다.

그러나 솔직히 나는 그다지 행복하지 않았기 때문에 내 자신의 솔루션을 목록에 추가하기로 결정했습니다. 여기에서 확인하세요 : $ modelFactory .

최종 결과 코드는 다음과 같이 표시됩니다.

var module = angular.module('services.zoo', ['modelFactory']);

module.factory('AnimalModel', function($modelFactory){
  return $modelFactory('api/zoo');
});

return module;

주로 모델 정의가 Angular와 매우 유사 ngResource하여 부족한 저수준 기능을 추가 하기 때문에 이것이 나머지보다 더 나은 솔루션이라고 생각합니다 . 초경량 (1.45k gzip / min)이며 몇 가지 작은 종속성 만 있습니다 (lodash, jquery 등 없음).


ModelCore ( https://github.com/klederson/ModelCore )는 다음과 같이 작동하며 구현하기가 매우 쉽습니다.

var ExampleApp = angular.module('ExampleApp', ['ModelCore']); //injecting ModelCore

ExampleApp.factory("Users",function(ModelCore) {
  return ModelCore.instance({
    $type : "Users", //Define the Object type
    $pkField : "idUser", //Define the Object primary key
    $settings : {
      urls : {
        base : "http://myapi.com/users/:idUser",
      }
    },
    $myCustomMethod : function(info) { //yes you can create and apply your own custom methods
        console.log(info);
    }
  });
});

//Controller
function MainCrtl($scope, Users) {
  //Setup a model to example a $find() call
  $scope.AllUsers = new Users();

  //Get All Users from the API
  $scope.AllUsers.$find();

  //Setup a model to example a $get(id) call
  $scope.OneUser = new Users();

  //Hey look there are promisses =)
  //Get the user with idUser 1 - look at $pkField
  $scope.OneUser.$get(1).success(function() {
    console.log("Done!",$scope.OneUser.$fetch());
});

Angular Rest-Mod 는 Angular 기반 모델 / ORM을위한 또 다른 좋은 옵션입니다.

Restmod는 Angular 내에서 RESTful API와 상호 작용할 수있는 객체를 생성합니다. 또한 컬렉션, 관계, 라이프 사이클 후크, 속성 이름 변경 등을 지원합니다.


ngResource에 대한 도우미의 또 다른 예입니다. 이것은 대부분의 서비스가 다음과 같다는 사실에 의존합니다.

http://host/api/posts
http://host/api/posts/123
http://host/api/posts/123/comments
http://host/api/posts/123/comments/456

So, the task is to make a helper that create AngularJS resource objects that maps on such services. Here it is:

'use strict';

var api = angular.module('api', ['ngResource']);

// RESTful API helper
api.addService = function (serviceNameComponents) {
    var serviceName = "";
    var resource = "/api"; // Root for REST services
    var params = {};

    serviceNameComponents.forEach(function (serviceNameComponent) {
        serviceName += serviceNameComponent;

        var lowerCaseServiceNameComponent = serviceNameComponent.toLowerCase();
        var collection = lowerCaseServiceNameComponent + 's';
        var id = lowerCaseServiceNameComponent + 'Id';

        resource += "/" + collection + "/:" + id;
        params[id] = '@' + id;
    });

    this.factory(serviceName, ['$resource',
        function ($resource) {
            return $resource(resource, {}, {
                    query: {
                        method: 'GET',
                        params: params,
                        isArray: true
                    },
                    save: {
                        method: 'POST',
                    },
                    update: {
                        method: 'PUT',
                        params: params,
                    },
                    remove: {
                        method: 'DELETE',
                        params: params,
                    }
                }
            );
        }
    ]);
}

So, to use it simply call this helper

api.addService(["Post"]);
api.addService(["Post", "Comment"]);

And then you can use Post and PostComment in code with needed params like :post_id

참고URL : https://stackoverflow.com/questions/16186887/angularjs-creating-objects-that-map-to-rest-resources-orm-style

반응형