Skip to content

171 view spring convert to ajax #191

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package net.onewordstory.core.adapters.display_data.story_data;

import org.jetbrains.annotations.NotNull;
import net.onewordstory.core.usecases.FullStoryDTO;
import org.jetbrains.annotations.NotNull;

/**
* Data necessary to seamlessly display the object. For example, if we are using Spring,
Expand All @@ -16,6 +16,7 @@
* @param likes number of likes this story has
* @param publishDateString A string representing the publish date of this story
*/

public record StoryDisplayData(int id,
@NotNull String title,
@NotNull String content,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package net.onewordstory.core.adapters.display_data.story_data;

/**
* Data necessary to seamlessly display the object. For example, if we are using Spring,
* this data should be directly passed to the Model. All display-related manipulation
* and computation should be taken care of and this should be directly displayable by
* passing necessary variables
*
* @param likes number of likes this story has
* @param numberOfComments number of comments this story has
* @param numberOfSuggestedTitles number of suggested titles
*/
public record StoryUpdateMetadata(int likes,
int numberOfComments,
int numberOfSuggestedTitles,
int titlesLikesInTotal) {
}
4 changes: 4 additions & 0 deletions src/main/java/net/onewordstory/spring/SpringApp.java
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

import java.util.Locale;
import java.util.Set;

@SpringBootApplication
@ComponentScan(basePackages = "net.onewordstory.core")
Expand Down Expand Up @@ -174,7 +175,10 @@ public UseCaseApiConfig(PostgresStoryRepo postgresStoryRepo,
!System.getenv("PROD").toLowerCase(Locale.ENGLISH).equals("true")) {
titlesRepo = new InMemoryTitlesRepo();
commentsRepo = new InMemoryCommentsRepo();

storyRepo = new InMemoryStoryRepo();
((InMemoryStoryRepo) storyRepo).saveStory("Hello! It is a test", 10000,
Set.of("Andrii", "Andrii II"));
} else {
storyRepo = postgresStoryRepo;
titlesRepo = postgresTitlesRepo;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,16 @@
import net.onewordstory.core.adapters.display_data.title_data.SuggestedTitleDisplayData;
import net.onewordstory.core.adapters.display_data.title_data.SuggestedTitleDisplayDataBuilder;
import net.onewordstory.core.adapters.view_models.*;
import net.onewordstory.core.usecases.Response;
import org.example.ANSI;
import org.example.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponentsBuilder;
import net.onewordstory.core.usecases.Response;

import java.util.*;
import java.util.List;

@Controller
public class StoryController {
Expand Down Expand Up @@ -53,30 +53,9 @@ public StoryController (GmlsController gmlsController,
}

@GetMapping("/")
public String index(Model model,
@RequestParam(name="get", defaultValue="latest") String storiesToGet )
throws InterruptedException {

public String index(@RequestParam(name="get", defaultValue="latest") String storiesToGet) {
// It is better to use a logger
System.out.println("Get /");

StoryListViewModel viewM;
Response res;
List<StoryDisplayData> stories;

if (storiesToGet.equals("liked")) {
viewM = gmlsController.getMostLikedStories(0, 100);
}
else { // Defaults to "latest"
viewM = glsController.getLatestStories(100);
}

res = viewM.getResponseAwaitable().await();
stories = viewM.getStoriesAwaitable().get();

// TODO: Add error handling and frontend message (e.g stories failed to load) if res is a fail code

model.addAttribute("stories", stories == null ? new ArrayList<>() : stories);

return "index";
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
package net.onewordstory.spring.controllers;

import com.fasterxml.jackson.databind.ObjectMapper;
import net.onewordstory.core.adapters.controllers.*;
import net.onewordstory.core.adapters.display_data.comment_data.CommentDisplayData;
import net.onewordstory.core.adapters.display_data.story_data.StoryDisplayData;
import net.onewordstory.core.adapters.display_data.story_data.StoryUpdateMetadata;
import net.onewordstory.core.adapters.display_data.title_data.SuggestedTitleDisplayData;
import net.onewordstory.core.adapters.view_models.GatViewModel;
import net.onewordstory.core.adapters.view_models.GscViewModel;
import net.onewordstory.core.adapters.view_models.StoryListViewModel;
import net.onewordstory.core.usecases.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.StringWriter;
import java.util.List;

import static net.onewordstory.spring.controllers.enums.StoriesRequestOptions.LIKED;

@RestController
public class StoryRestController {

private final GmlsController gmlsController;
private final GlsController glsController;
private final GsbiController gsbiController;
private final GatController gatController;

private final GscController gscController;

private final ObjectMapper mapper;
@Autowired
public StoryRestController(GmlsController gmlsController, GlsController glsController,
GsbiController gsbiController, GatController gatController,
GscController gscController) {
this.gmlsController = gmlsController;
this.glsController = glsController;
this.gsbiController = gsbiController;
this.gatController = gatController;
this.gscController = gscController;
mapper = new ObjectMapper();
}

private String mapToJson(Object object) {
StringWriter writer = new StringWriter();
try {
mapper.writeValue(writer, object);
} catch (IOException ex) {
return "";
}
return writer.toString();
}

private StoryListViewModel getCorrespondingStories(String storiesToGet) {
if (storiesToGet.equals(LIKED.toString()))
return gmlsController.getMostLikedStories(0, 100);
// Defaults to "latest"
return glsController.getLatestStories(100);
}

@GetMapping(path = "/stories")
public String getStories(@RequestParam(name="get", defaultValue="latest") String storiesToGet) throws InterruptedException {
StoryListViewModel viewM = getCorrespondingStories(storiesToGet);
List<StoryDisplayData> result = viewM.getStoriesAwaitable().await();
return mapToJson(result);
}

@GetMapping(path="/api/story/lastStory")
public String getLastStoryId(@RequestParam(name="get", defaultValue="latest") String storiesToGet)
throws InterruptedException {
StoryListViewModel viewModel = getCorrespondingStories(storiesToGet);
StoryDisplayData result = viewModel.getStoriesAwaitable().await().get(0);
return mapToJson(result);
}


//TODO Simplify this code just to grab the number
@GetMapping("/api/story/metadata/{id}")
public String storyUpdateMetadata(@PathVariable int id) throws InterruptedException {
StoryListViewModel gsbiViewM = gsbiController.getStoryById(id);
GatViewModel gatViewM = gatController.getAllTitles(id);
GscViewModel gscViewM = gscController.getStoryComments(id);

Response gatRes = gatViewM.getResponseAwaitable().await();
Response gsbiRes = gsbiViewM.getResponseAwaitable().await();
Response gscRes = gscViewM.getResponseAwaitable().await();

List<StoryDisplayData> stories = gsbiViewM.getStoriesAwaitable().get();
List<SuggestedTitleDisplayData> titles = gatViewM.getSuggestedTitlesAwaitable().get();
List<CommentDisplayData> comments = gscViewM.getCommentsAwaitable().get();
StoryUpdateMetadata result = null;
if (gsbiRes.getCode() == Response.ResCode.SUCCESS &&
gatRes.getCode() == Response.ResCode.SUCCESS &&
gscRes.getCode() == Response.ResCode.SUCCESS) {
assert titles != null && stories != null && comments != null;
int likesInTotal = titles.stream().
map(SuggestedTitleDisplayData::numUpvotes).reduce(0, Integer::sum);
StoryDisplayData storyDisplayData = stories.get(0);
result = new StoryUpdateMetadata(
storyDisplayData.likes(),
comments.size(),
titles.size(),
likesInTotal
);
}
else {/* TODO: Add error handling and frontend message (e.g stories failed to load) */}
return mapToJson(result);
}

@GetMapping("/api/story/comments/{id}")
public String getStoryComments(@PathVariable int id) throws InterruptedException {
GscViewModel gscViewM = gscController.getStoryComments(id);
Response response = gscViewM.getResponseAwaitable().await();
List<CommentDisplayData> comments = gscViewM.getCommentsAwaitable().get();
if (response.getCode() == Response.ResCode.SUCCESS) {
return mapToJson(comments);
}
return "";
}

@GetMapping("/api/story/title/{id}")
public String getStoryTitle(@PathVariable int id) throws InterruptedException {
StoryListViewModel gsbiViewM = gsbiController.getStoryById(id);
Response gsbiRes = gsbiViewM.getResponseAwaitable().await();
List<StoryDisplayData> stories = gsbiViewM.getStoriesAwaitable().get();
if (gsbiRes.getCode() == Response.ResCode.SUCCESS) {
assert stories != null;
return stories.get(0).title();
} else {/* TODO: Add error handling and frontend message (e.g stories failed to load) */}
return "";
}

@GetMapping("/api/story/titles/{id}")
public String getStorySuggestedTitles(@PathVariable int id) throws InterruptedException {
GatViewModel gatViewM = gatController.getAllTitles(id);
Response response = gatViewM.getResponseAwaitable().await();
List<SuggestedTitleDisplayData> titles = gatViewM.getSuggestedTitlesAwaitable().get();
if (response.getCode() == Response.ResCode.SUCCESS) {
return mapToJson(titles);
}
return "";
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package net.onewordstory.spring.controllers.enums;

public enum StoriesRequestOptions {

LIKED, LATEST;

@Override
public String toString() {
return this.name().toLowerCase();
}

}
44 changes: 44 additions & 0 deletions src/main/resources/static/js/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
const SortingMethods = {
LATEST: "latest",
LIKED: "liked"
};

const simpleGetOption = {method: 'GET'};

const sortingMethodParameterName = "get";
const currentSortingMethodPrefix = `?${sortingMethodParameterName}=`;
let currentSortingMethodSuffix = SortingMethods.LIKED;

let lastStory = {};

// Call the function when this javascript file has been loaded
loadNewStories();

let callId = setInterval(loadNewStories, 1000);
function toggleSortingMethod() {
clearInterval(callId);
lastStory = null;
currentSortingMethodSuffix = currentSortingMethodSuffix === SortingMethods.LATEST ?
SortingMethods.LIKED : SortingMethods.LATEST;
loadNewStories();
callId = setInterval(loadNewStories, 1000);
}
function loadNewStories() {
const restUrl = `/stories${currentSortingMethodPrefix}${currentSortingMethodSuffix}`;
console.log(`Fetching from: ${restUrl}`);
fetch(restUrl, simpleGetOption).then(response => response.json()).then(response =>
{
// Building HTML
const html = [];
response.forEach(element => {
html.push('<div class="story" id = "story1">');
html.push(`<a href="/story-${element.id}"><h2>${element.title}</h2></a>`);
html.push(`<span style="color:darkblue"> ${element.likes}</span>`);
html.push(`<p>Published: ${element.publishDateString} </p>`);
html.push(`<h4>Authors: <span> ${element.authorString} </span></h4>`);
html.push(`<p> ${element.content} </p>`);
html.push('</div>');
});
document.getElementById("stories_wrapper").innerHTML = html.join("");
});
}
Loading