Techioz Blog

モバイルデバイスがすでに登録されているかどうかを確認するにはどうすればよいですか

概要

Amazon SNS に Amazon AWS Ruby SDK を使用していますが、デバイスがすでに登録されているため問題が発生しています。デバイスが再度登録されると、AWS::SNS::Errors::InvalidParameter のようなエラーが発生する場合があります 無効なパラメータ: トークン 理由: エンドポイント arn:aws:sns:us-east-1:**** はすでに同じものに存在しますトークンですが、属性が異なります。エンドポイントがすでに存在するかどうかを確認するにはどうすればよいですか?さらに重要なことに、特定のトークンのエンドポイントを取得するにはどうすればよいですか?

解決策

BvdBijl のアイデアのおかげで、既存のメソッドが見つかった場合は削除して追加する拡張メソッドを作成しました。

using System;
using System.Text.RegularExpressions;
using Amazon.SimpleNotificationService;
using Amazon.SimpleNotificationService.Model;

namespace Amazon.SimpleNotificationService
{
    public static class AmazonSimpleNotificationServiceClientExtensions
    {
        private const string existingEndpointRegexString = "Reason: Endpoint (.+) already exists with the same Token";
        private static Regex existingEndpointRegex = new Regex(existingEndpointRegexString);
        public static CreatePlatformEndpointResponse CreatePlatformEndpointIdempotent(
            this AmazonSimpleNotificationServiceClient client,
            CreatePlatformEndpointRequest request)
        {
            try
            {
                var result = client.CreatePlatformEndpoint(request);
                return result;
            }
            catch (AmazonSimpleNotificationServiceException e)
            {
                if (e.ErrorCode == "InvalidParameter")
                {
                    var match = existingEndpointRegex.Match(e.Message);
                    if (match.Success) {
                        string arn = match.Groups[1].Value;
                        client.DeleteEndpoint(new DeleteEndpointRequest
                        {
                             EndpointArn = arn,
                        });
                        return client.CreatePlatformEndpoint(request);
                    }
                }
                throw;
            }
        }
    }
}