A User Profile in the Reddit App – Reddit应用程序中的用户资料

最后修改: 2015年 6月 25日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this article we’re going to be building a Profile for the user of our Reddit application – to allow them to configure user specific preferences.

在这篇文章中,我们将为我们的Reddit应用程序的用户建立配置文件 – 允许他们配置用户的特定偏好。

The goal is simple – instead of having the user fill in the same data each time they schedule a new post, they can set it once – in the preferences of their profile. Of course the user can always tune these settings for each post – but the idea is they don’t have to.

目标很简单–与其让用户在每次安排新的帖子时填写相同的数据,他们可以一次性设置–在他们个人资料的偏好中。当然,用户可以随时为每篇帖子调整这些设置–但我们的想法是他们不必这样做。

2. The Preference Entity

2.Preference实体

Overall, most things that can now be configured in the applications are going to become globally configurable in the user profile.

总的来说,现在可以在应用程序中配置的大多数东西都将成为用户配置文件中的全球配置

First, let’s start with a Preference entity:

首先,让我们从一个Preference实体开始。

@Entity
public class Preference {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String email;

    private String subreddit;

    private boolean sendReplies;

    // for post re-submission
    private int noOfAttempts;
    private int timeInterval;
    private int minScoreRequired;
    private int minUpvoteRatio;
    private boolean keepIfHasComments;
    private boolean deleteAfterLastAttempt;
}

So, what can we now configure? Simply put – defaults for pretty much every setting in the application.

那么,我们现在可以配置什么?简单地说–应用程序中几乎所有设置的默认值

We’re also storing the email of the user to allow them to receive notifications about what’s happening to their posts.

我们也在存储用户的电子邮件,以便让他们收到关于其帖子发生的通知。

Now, let’s link the preferences to the user:

现在,让我们将偏好链接到用户身上

@Entity
public class User {
    ...
    
    @OneToOne
    @JoinColumn(name = "preference_id")
    private Preference preference;
}

As you can see, we have a simple one-to-one relation between User and Preference.

正如你所看到的,我们在UserPreference之间有一个简单的一对一的关系。

3. Simple Profile Page

3.简单的个人资料页面

First, let’s create our simple profile page:

首先,让我们创建我们简单的个人资料页面。

<form >
    <input type="hidden" name="id" />
    <input name="email" type="email"/>
    <input name="subreddit"/>
    ...
   <button onclick="editPref()" >Save Changes</button>
</form>
<script>
$(function() {
    $.get("user/preference", function (data){
        $.each(data, function(key, value) {
            $('*[name="'+key+'"]').val(value);
        });
    });
});
function editPref(){
    var data = {};
	$('form').serializeArray().map(function(x){data[x.name] = x.value;});
	$.ajax({
        url: "user/preference/"+$('input[name="id"]').val(),
        data: JSON.stringify(data),
        type: 'PUT',
        contentType:'application/json'
    }).done(function() { window.location.href = "./"; })
      .fail(function(error) { alert(error.responseText); }); 
}
</script>

Nothing fancy here – just some plain HTML and JavaScript.

这里没有什么花哨的东西 – 只是一些普通的HTML和JavaScript。

Let’s also add a quick link to the new profile:

让我们也添加一个快速链接到新的个人资料。

<h1>Welcome, <a href="profile" sec:authentication="principal.username">username</a></h1>

4. The API

4.API

And here the controller, for creating and editing user’s preferences:

这里是控制器,用于创建和编辑用户的偏好。

@Controller
@RequestMapping(value = "/user/preference")
public class UserPreferenceController {

    @Autowired
    private PreferenceRepository preferenceReopsitory;

    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public Preference getCurrentUserPreference() {
        return getCurrentUser().getPreference();
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    @ResponseStatus(HttpStatus.OK)
    public void updateUserPreference(@RequestBody Preference pref) {
        preferenceReopsitory.save(pref);
        getCurrentUser().setPreference(pref);
    }
}

Finally, we need to make sure that, when the user is created, its preferences are also inintialized:

最后,我们需要确保,当用户被创建时,其偏好也被惯性化了。

public void loadAuthentication(String name, OAuth2AccessToken token) {
    ...
    Preference pref = new Preference();
    preferenceReopsitory.save(pref);
    user.setPreference(pref);
    userReopsitory.save(user);
    ...   
}

5. Load/Use Preferences

5.加载/使用首选项

Now – let’s see how to use these preferences and fill them in whenever they’re required.

现在–让我们看看如何使用这些偏好,并在需要的时候填写它们。

We’ll start with the main Post Schedule page – where we’ll load in the preferences of the user:

我们将从主Post Schedule页开始–在这里我们将加载用户的偏好。

$(function() {
    $.get("user/preference", function (data){
        $.each(data, function(key, value) {
            $('*[name="'+key+'"]').val(value);
        });
    });
});

6. Testing and Conclusion

6.测试和结论

We’re almost done – we just need to implement some basic integration tests for the new Profile entity we just introduced.

我们几乎已经完成了 – 我们只需要为我们刚刚引入的新的Profile实体实现一些基本的集成测试。

For the most part, we’re simply going to be extending the existing base persistence test and inherit a battery of tests from that.

在大多数情况下,我们将简单地扩展现有的基础持久性测试,并从中继承一系列的测试。

Finally – we can wrap up the new user profile functionality – users are now able to set up their own preferences.

最后–我们可以总结一下新的用户档案功能–用户现在能够设置自己的偏好。