Created
December 6, 2014 20:37
-
-
Save scionwest/91be12fa65e615dddcd0 to your computer and use it in GitHub Desktop.
UserRepository
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class UserRepository : IUserRepository | |
{ | |
/// <summary> | |
/// Asks the data store to create a new user with the given data.. | |
/// </summary> | |
/// <param name="data">The data that represents a user.</param> | |
/// <param name="password">The password.</param> | |
/// <returns> | |
/// Returns a session token that can be used to preserve a user session. | |
/// </returns> | |
public async Task<string> CreateUser(Dictionary<string, string> data, string password) | |
{ | |
// We have to convert the keys to camelcase for Parse. | |
// Regular expressions weren't working. Need to revist them as this is | |
// creating a large of garbage. | |
var convertedKeys = data.ToDictionary( | |
key => | |
{ | |
string firstChar = key.Key.Substring(0, 1).ToLower(); | |
string remainder = key.Key.Substring(1); | |
return string.Format("{0}{1}", firstChar, remainder); | |
}, | |
element => element.Value); | |
var json = JsonConvert.SerializeObject(convertedKeys); | |
// Create our httpClient and post our content to the users path. | |
HttpClient httpClient = ParseRestHelper.CreateHttpClient(); | |
HttpResponseMessage response = await ParseRestHelper | |
.PostAsync(httpClient, "users", json); | |
// Make sure the response codes are good. | |
try | |
{ | |
await this.ValidateResponseCodes(response); | |
} | |
catch (Exception) | |
{ | |
return string.Empty; | |
} | |
// Grab the session token and save it for future use. | |
json = await response.Content.ReadAsStringAsync(); | |
string sessionToken = JObject | |
.Parse(json) | |
.GetValue("sessionToken") | |
.ToString(); | |
return sessionToken; | |
} | |
/// <summary> | |
/// Retrieves user data for a user who has a matching username and password.. | |
/// </summary> | |
/// <param name="username">The username.</param> | |
/// <param name="password">The password.</param> | |
/// <returns> | |
/// Returns a collection of data that can be used to construct a user object. | |
/// </returns> | |
public async Task<Dictionary<string, string>> RetrieveUser(string username, string password) | |
{ | |
HttpClient httpClient = ParseRestHelper.CreateHttpClient(); | |
HttpResponseMessage response = await ParseRestHelper.GetAsync( | |
client: httpClient, | |
path: "login", | |
parameters: new[] | |
{ | |
new KeyValuePair<string, string>("username", username), | |
new KeyValuePair<string, string>("password", password), | |
} | |
); | |
await this.ValidateResponseCodes(response); | |
// Conver the json return result to a dictionary. | |
string json = await response.Content.ReadAsStringAsync(); | |
Dictionary<string, string> data = | |
JsonConvert.DeserializeObject<Dictionary<string, string>>(json); | |
// Return the data. | |
return this.PrepareData(data); | |
} | |
/// <summary> | |
/// Retrieves the user. | |
/// </summary> | |
/// <param name="token">The token.</param> | |
/// <returns>Returns a collection of data that can be used to construct a user.</returns> | |
public async Task<Dictionary<string, string>> RetrieveUser(string token) | |
{ | |
if (string.IsNullOrWhiteSpace(token)) | |
{ | |
return null; | |
} | |
var httpClient = ParseRestHelper.CreateHttpClient( | |
new KeyValuePair<string, string>( | |
"X-Parse-Session-Token", | |
token)); | |
HttpResponseMessage response = await ParseRestHelper.GetAsync(httpClient, "users/me"); | |
await this.ValidateResponseCodes(response); | |
// Conver the json return result to a dictionary with the key's in pascal casing. | |
string json = await response.Content.ReadAsStringAsync(); | |
Dictionary<string, string> data = JsonConvert.DeserializeObject<Dictionary<string, string>>(json); | |
// Return the data, converted for consumption by the app. | |
return this.PrepareData(data); | |
} | |
/// <summary> | |
/// Prepares the data that will be used when constructing a user object. | |
/// </summary> | |
/// <param name="data">The data.</param> | |
/// <returns></returns> | |
private Dictionary<string, string> PrepareData(Dictionary<string, string> data) | |
{ | |
string valueForKey = data["objectId"]; | |
data.Remove("objectId"); | |
data.Add("userId", valueForKey); | |
valueForKey = data["createdAt"]; | |
data.Remove("createdAt"); | |
data.Add("createdDate", valueForKey); | |
valueForKey = data["updatedAt"]; | |
data.Remove("updatedAt"); | |
data.Add("updatedDate", valueForKey); | |
return data.ToDictionary( | |
key => | |
{ | |
string firstChar = key.Key.Substring(0, 1).ToUpper(); | |
string remainder = key.Key.Substring(1); | |
return string.Format("{0}{1}", firstChar, remainder); | |
}, | |
value => value.Value); | |
} | |
/// <summary> | |
/// Handles the error response. | |
/// </summary> | |
/// <param name="response">The response from the server.</param> | |
/// <returns>Returns void</returns> | |
/// <exception cref="System.Exception">Throws an exception with the server response message as the error.</exception> | |
private async Task<string> ValidateResponseCodes(HttpResponseMessage response) | |
{ | |
if (response.IsSuccessStatusCode) | |
{ | |
return string.Empty; | |
} | |
string result = await response.Content.ReadAsStringAsync(); | |
var statusContent = new { code = string.Empty, error = string.Empty }; | |
statusContent = JsonConvert.DeserializeAnonymousType(result, statusContent); | |
throw new Exception(statusContent.error); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment