Skip to content

Latest commit

 

History

History
88 lines (68 loc) · 3.03 KB

README_step02.md

File metadata and controls

88 lines (68 loc) · 3.03 KB

02. Connect to your Astra database

License Apache2 Discord Actions Status Netlify Status

[🏠 Back to Table of Contents]

1. Creating the insertGame endpoint

See the complete code solution here

  1. 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)

  1. 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;
  1. 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 a 500. 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.

Go to Create Client state