[🏠 Back to Table of Contents]
- [Part1 - Setup environment and tools]
- [Part2 - Create a REST API with netlify]
See the complete code solution here
- We will need to get a game id from someone, and also a payload we need from the user
let gameId;
let gamePayload;
In Netlify, you get your parameter from the path, and parse our event body
gameId = event.path.split("insertGame/")[1];
gamePayload = JSON.parse(event.body);
Validation step: If we dont get it, a 400 will be returned and you will get an error message
...
} catch (e) {
return {
statusCode: 400,
body: JSON.stringify({ message: "must provide a valid game ID" }),
};
}
All this should statisfy our second test ( we need to get valid game id)
- Then we are going to connect to Astra, we are going to give the Astra client our environmental variable credentials so that you can connect to Astra. We are importing our Astra client and connecting it to Astra
const astraClient = await astra.createClient({
baseUrl: `https://${process.env.ASTRA_DB_ID}-${process.env.ASTRA_DB_REGION}.apps.astra.datastax.com`,
username: process.env.ASTRA_DB_USERNAME,
password: process.env.ASTRA_DB_PASSWORD,
});
const namespace = process.env.ASTRA_DB_KEYSPACE;
const collection = process.env.GAMES_COLLECTION;
- Then we are going to try to take that input and create a game from it with our client. If it works, we get back a
200
. If it fails, we will get back a500
. This should statify both test 1 and test 2.
try {
const res = await astraClient.put(
`/namespaces/${namespace}/collections/${collection}/${gameId}`,
gamePayload
);
return {
statusCode: 200,
body: JSON.stringify(res.jsonResponse),
};
} catch (e) {
console.error(e);
return {
statusCode: 500,
body: JSON.stringify(e),
};
}
};
See the complete code solution here
Now all of our tests should pass. Let's run our tests once again:
npm run tests: functions
|
Click below to move to the next section.