Adding a Topic ID to a Google Classroom assignment - google-apps-script

I'm trying to create an assignment using Google Apps script and place it under a topic that is also created in the same script. I have no problem creating an assignment when no topicId is specified, but as soon as I try to specify a topicId , I receive the following error when I run the script: API call to classroom.courses.courseWork.create failed with error: Invalid JSON payload received. Unknown name "Test Topic"
Here is my code:
function makeStuff() {
var topic = {
name: "Test Topic"
};
Classroom.Courses.Topics.create(topic, "46088716060");
var TWS1 = {
title: "Test Worksheet 1",
state: "DRAFT",
materials: [
{
driveFile:{
driveFile: {
id: "1REOs1RYtyVTX67VnJezjWf-wm7HqDVexeaeiQL3-HvM",
},
shareMode: "STUDENT_COPY"
}
}
],
workType: "ASSIGNMENT",
topicId: {
name: "Test Topic"
}
};
Classroom.Courses.CourseWork.create(TWS1, "46088716060")
}
Is it possible to reference the topicId by name, or assign the topicId number that is created in the script to a variable that can be referenced?

To create a topic, you only need to supply a name (the topic name is not its id, only the API can generate ids). The Classroom API then creates the topic, which it returns as an object with the topicId property defined on it, as seen below;
var courseId = "46088716060";
var topicName = "Test Topic";
var topic = Classroom.Courses.Topics.create({name:topicName}, courseId);
var topicId = topic.topicId;
You then use that topicId when creating coursework.

Related

How to check if the response includes specified value and if so - end test in Postman

I'm learning Postman test scripts and I am stuck with one exercise. I need to check if the response includes specified value (one of the planet from array is called Tatooine). Body response:
"results": [
{
"name": "Tatooine",
"rotation_period": "23",
"orbital_period": "304",
"diameter": "10465",
{
"name": "Alderaan",
"rotation_period": "24",
"orbital_period": "364",
"diameter": "12500",
},
I created this script:
const jsonData = pm.response.json();
pm.test("Your test name", function () {
for (let i = 0; i <= jsonData.results.length; i++) {
pm.expect(jsonData.results[i].name).to.include("Tatooine")};
});
But I don't know how to get out of the loop and mark test as "passed" after finding searched value.
I assume you want to verify that at least there is a name Tatooine.
Step 1: Get all names
const jsonData = pm.response.json();
let names = _.map(jsonData.results, "name");
Step 2: Validate the array names contains Tatooine
pm.test("Your test name", function () {
pm.expect(names).to.include("Tatooine")
});

Parsing JSON in Office Scripts - not iterable

I am attempting to parse JSON in Office Scripts that prints the headings and row information on the sheet. I'm successfully fetching the data, but I keep getting the error message that my information is not iterable on the "for" line.
async function main(workbook: ExcelScript.Workbook) {
// Call the API
const response = await fetch('WEBADDRESSHERE');
const sitedata: siteInformation[] = await response.json();
// Set the types for rows
const rows: (string | number)[][]=[];
// Iterate through the data and get the row headings
for (let site of sitedata){
rows.push([site.SiteID, site.SiteDescription, site.EffectiveDate, site.DataPresent]);
}
// Get the current sheet
const sheet = workbook.getActiveWorksheet();
// Set the range to start writing the details
const range = sheet.getRange('A2').getResizedRange(rows.length - 1, rows[0].length - 1);
range.setValues(rows);
return;
}
interface siteInformation {
SiteID: string;
SiteDescription: string;
EffectiveDate: date;
DataPresent: string;
}
This is the sample JSON I'm working with.
{
"1": {
"SiteID": "2",
"SiteDescription": "SiteA",
"EffectiveDate": "2022-08-01",
"DataPresent": "Yes"
},
"2": {
"SiteID": "2",
"SiteDescription": "SiteA",
"EffectiveDate": "2022-08-02",
"DataPresent": "Yes"
}
}
There are a few things going on here
I believe the reason you're getting the "not iterable" error is because you're using the wrong loop. To loop through a JSON dictionary, you need to use for...in... not for...of...
Second, when you update the loop, you'll get the key back as the element. So you need to use the key with the sitedata to get the specific JSON element you're trying to loop through.
Lastly, although it's not necessary, you listed the date type as a type in the interface. This is showing an error on the office scripts IDE for me. So you may want to update that to string.
You can see a code snippet with the updates below:
async function main(workbook: ExcelScript.Workbook) {
// Call the API
const sitedataStr = `{
"1": {
"SiteID": "1",
"SiteDescription": "SiteA",
"EffectiveDate": "2022-08-01",
"DataPresent": "Yes"
},
"2": {
"SiteID": "2",
"SiteDescription": "SiteA",
"EffectiveDate": "2022-08-02",
"DataPresent": "Yes"
}
}`
let sitedata: siteInformation = JSON.parse(sitedataStr)
// Set the types for rows
const rows: (string | number)[][] = [];
// Iterate through the data and get the row headings
for (let key in sitedata) {
let site:siteInformation = sitedata[key]
rows.push([site.SiteID, site.SiteDescription, site.EffectiveDate, site.DataPresent]);
}
}
interface siteInformation {
SiteID: string;
SiteDescription: string;
EffectiveDate: string;
DataPresent: string;
}

adding contact to existing group (people api migration)

Trying to get all this stuff migrated from the much simpler Contact API before it's switched before it's switched off in a few days. I'm able to add people now, but adding them to the group that is shared company wide isn't working.
// https://stackoverflow.com/questions/64095816/add-a-created-contact-to-a-group-by-people-api-using-google-apps-script
function createContactLead(lead) {
var contactResource = {
"names": [{
"displayNameLastFirst": lead["FirstName"] + " " + lead["LastName"],
"familyName": lead["LastName"],
"givenName" : lead["FirstName"]
}],
"phoneNumbers": [{
'value': lead["Phone"],
'type' : 'mobile',
}],
"emailAddresses": [{
'value': lead["Email"]
}],
"addresses": [{
"city": lead["city"],
"region": lead["state"]
}],
}
var peopleResource = People.People.createContact(contactResource);
var contactResourceName = peopleResource["resourceName"];
groupName = "Leads (Shared)";
var groups = People.ContactGroups.list()["contactGroups"];
var group = groups.find(group => group["name"] === groupName);
console.log(group);
var groupResourceName = group["resourceName"];
console.log("group resource name %s", groupResourceName);
var membersResource = {
"resourceNamesToAdd": [
contactResourceName
]
}
People.ContactGroups.Members.modify(membersResource, groupResourceName);
}
It definitely finds the group but trying to modify it results in " Invalid value at 'resource_names_to_add' (resource_names_to_add), Starting an object on a scalar field"
Execution log
12:34:02 PM Notice Execution started
12:34:03 PM Info { formattedName: 'Leads (Shared)',
groupType: 'USER_CONTACT_GROUP',
metadata: { updateTime: '2021-02-08T17:56:34.066Z' },
name: 'Leads (Shared)',
memberCount: 89,
etag: 'XadlO6et7QY=',
resourceName: 'contactGroups/27ee381f0e7d94e7' }
12:34:03 PM Info group resource name contactGroups/27ee381f0e7d94e7
12:34:03 PM Error
GoogleJsonResponseException: API call to people.contactGroups.members.modify failed with error: Invalid value at 'resource_names_to_add' (resource_names_to_add), Starting an object on a scalar field
createContactLead # test.gs:41
driver # test.gs:68
Thanks in advance!
Apparently I had a bug early on where I wasn't pulling out the "resourceName" from the people object. The code has since been updated in the question. Once that was fixed everything worked. I'll leave this up as it wasn't easy to get right.

How to query to return post starred by specific user?

I am playing around with the firebase sample code of realtime database https://github.com/firebase/quickstart-android/tree/master/database
I am new to JSON and i tried many method and cannot figure out a query that return post starred by user B (so that user B can see the post he liked before)
Or do I need to build another tree?
Query I tried:
public Query getQuery(DatabaseReference databaseReference) {
// All my posts
return databaseReference.child("posts").child("stars").child(getUid()).equalTo(true);
}
My JSON tree:
{
"posts":{
"-KMPiC6Okoe2dd35keT6":{
"author":"user A",
"body":"post by user A",
"starCount":1,
"stars":{
"user B":true
},
"timeStamp":"1468253393509",
"title":"post by user1",
"uid":"user A",
"viewCount":0
},
"-KMPiIHQXrZIfnv2uNV-":{
"author":"user B",
"body":"post by user B",
"starCount":0,
"timeStamp":"1468253419640",
"title":"post by user B",
"uid":"user B",
"viewCount":0
}
},
"user-posts":{
"user A":{
"-KMPiC6Okoe2dd35keT6":{
"author":"user A",
"body":"post by user A",
"starCount":1,
"stars":{
"user B":true
},
"timeStamp":"1468253393509",
"title":"post by user A",
"uid":"user A",
"viewCount":0
}
},
"user B":{
"-KMPiIHQXrZIfnv2uNV-":{
"author":"lui",
"body":"post by user 2",
"starCount":0,
"timeStamp":"1468253419640",
"title":"post by user 2",
"uid":"user B",
"viewCount":0
}
}
},
"users":{
"user A":{
"email":"userA#gmail.com",
"username":"user A"
},
"user B":{
"email":"userB#gmail.com",
"username":"user B"
}
}
}
First, you are missing a reference:
// Old
databaseReference.child("posts").child("stars").child(getUid()).equalTo(true);
// New
databaseReference.child("posts").child(some-post).child("stars").child(getUid()).equalTo(true);
But still this would be very difficult or even impossible to do that search straight up, without needing to sift through the data returned.
What I advise to do is create a users tree and write the starred posts to the specific user instead of the users to the posts. e.g.:
"users": {
"userA": {
"starred": {
"-KMP3242nf23nfn23": {
"author": "userB",
"post": "-KMPiC6Okoe2dd35keT6"
},
"-KMPiIHQXrZIfnv2uNV-": {
"author": "userB",
"post": "-KMPiC6Okoe2dd35keT6"
},
...
}
}
}
(push the new starred posts onto starred)
Then you could make a query as such:
// Get a list of posts starred
... databaseReference.child("users").child(getUid()).child(starred);
// Iterate through and get value of `author` and `post`
...
// Store the values in variables
var author = "...";
var post = "...";
// Make the call
return databaseReference.child("posts").child(post);
Other reference: Firebase - How do I write multiple orderByChild for extracting data?
Comment with any questions.
This is pretty straight forward deep query
Here's a Swift solution (using v2.x Firebase) since the platform was not specified.
let ref = self.myRootRef.childByAppendingPath("posts")
ref.queryOrderedByChild("stars/user B").queryEqualToValue(true)
.observeEventType(.Value, withBlock: { snapshot in
if ( snapshot.value is NSNull ) {
print("not found")
} else {
for child in snapshot.children {
let key = child.key as String
let author = child.value["author"] as! String
print("key = \(key) author = \(author)")
}
}
})
this will print
key = -KMPiC6Okoe2dd35keT6 author = user A
and if there are other nodes that also match the criteria, they will print as well.

Unable to sort Dgrid

var CustomGrid = declare([Grid, Keyboard, Selection]);
var questionGrid = new CustomGrid({
store: questionCacheStore,
columns: [
editor({
label: "Questions",
field: "question",
editor: "text",
editOn: "dblclick",
sortable:true})
],
selectionMode: "single",
cellNavigation: false
}, "questions");
I am new to Dgrid. So, please do bear with me .
i was able to populate the dgrid with a JsonStore content. But when i click on the column 'Questions', it doesn't get sorted as in local data store.instead it shows an error Uncaught TypeError: Object [object Object] has no method 'sort'. Is it required to define such a method . If so, how and where should i define it ?
I am not the person to answer your J2EE question. I asked that question recently. The solution that I found was to inject the HttpServletRequest directly. This allowed me access to the query string parameters. From there I was able to get the sort direction (ascending, descending) and column to sort. Hopefully the snippets below will help.
Example Grid Setup
require(["dojo/store/JsonRest", "dojo/store/Memory", "dojo/store/Cache",
"dojo/store/Observable", "dgrid/OnDemandGrid", "dojo/_base/declare", "dgrid/Keyboard",
"dgrid/Selection", "dojo/domReady!"],
function(JsonRest, Memory, Cache, Observable, Grid, declare, Keyboard, Selection) {
var rest = new JsonRest({target:"/POC_Admin/rest/Subcategory/", idProperty: "subcatId"});
var cache = new Cache(rest, new Memory({ idProperty: "subcatId" }));
var store = new Observable(cache);
var CustomGrid = declare([ Grid, Keyboard, Selection ]);
var grid = new CustomGrid({
columns: {
subcatId: "ID",
name: "Name"
},
store: store
}, "grid");
grid.on("dgrid-select", function(event){
// Report the item from the selected row to the console.
console.log("Row selected: ", event.rows[0].data);
});
grid.startup();
});
Example Rest GET
#Context private HttpServletRequest servletRequest;
#GET
#Path("")
#Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8")
public String getSubcategories(#QueryParam("name") String name) throws IOException {
//Respond to a QueryString value.
if (servletRequest.getQueryString() != null && servletRequest.getQueryString().length() > 0) {
String querystringKey = servletRequest.getQueryString();
System.out.println("QSKey = " + querystringKey);
System.out.println("Substr: " + querystringKey.substring(0, 4));
if (querystringKey.length()>4) {
if (querystringKey.substring(0, 4).contains("sort")) {
//We have the sort request.
}
}
}
//Return all results otherwise from your DAO at this point
}